PHP将JSON对象返回给Javascript [AJAX CALL]无法正常工作

时间:2022-05-20 19:06:24

I have made Ajax calls before, and let them return JSON objects, which worked, but I dont seem to get it working anymore.

我之前已经进行过Ajax调用,并让它们返回JSON对象,这些对象有效,但我似乎不再让它工作了。

This is my ajax call:

这是我的ajax电话:

function sendContactForm() {
var nameInput = $('#nameInput').val();
var emailInput = $('#emailInput').val();
var subjectInput = $('#subjectInput').val();
var msgInput = $('#msgInput').val();

$.ajax({
    // Make a POST request to getfile       
    url: "/service/contactmail",
    data: {
        nameInput: nameInput,
        emailInput: emailInput,
        subjectInput: subjectInput,
        msgInput: msgInput
    },
    method: "post",
    // And run this on success      
    success: function (data) {
        if (data.send === 1){
            // VERZONDEN
        }else if(data.send === 2){
            // VARS NIET INGEVULT
        }else{
            // IETS ANDERS FOUT
        }
        console.log(data);
    },
    error: function () {
        alert("fout");
    }
});
}

and this is my php function:

这是我的PHP功能:

private function sendContactForm() {
    $output = array(
        "test" => null,
        "send" => null
    );
    if ($this->fillVariables()) {
        $this->sendMail();
        $output['send'] = 1;
        return true;
    } else {
        $output['send'] = 2;
        return false;
    }
    header("Content-Type: application/json");
    echo json_encode($output);
}

but the variable "data" has a value of: "" (empty string) There are no other echo's in my php class, so that should not be the problem.

但变量“data”的值为:“”(空字符串)我的php类中没有其他echo,所以这不应该是问题。

Thanks in advance,
Mats de Waard

在此先感谢Mats de Waard

1 个解决方案

#1


1  

The return's in your if statements are stopping the execution of this function before you can generate the result back to the page.

if语句中的return将停止执行此函数,然后才能将结果生成回页面。

private function sendContactForm() {

    $output = array(
        "test" => null,
        "send" => null
    );
    if ($this->fillVariables()) {
        $this->sendMail();
        $output['send'] = 1;
        //return true;
    } else {
        $output['send'] = 2;
        //return false;
    }
    header("Content-Type: application/json");
    echo json_encode($output);
}

#1


1  

The return's in your if statements are stopping the execution of this function before you can generate the result back to the page.

if语句中的return将停止执行此函数,然后才能将结果生成回页面。

private function sendContactForm() {

    $output = array(
        "test" => null,
        "send" => null
    );
    if ($this->fillVariables()) {
        $this->sendMail();
        $output['send'] = 1;
        //return true;
    } else {
        $output['send'] = 2;
        //return false;
    }
    header("Content-Type: application/json");
    echo json_encode($output);
}