简体   繁体   English

PHP 将 JSON 对象返回给 Javascript [AJAX CALL] 不起作用

[英]PHP Return JSON object to Javascript [AJAX CALL] not working

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类中没有其他回声,所以这应该不是问题。

Thanks in advance,提前致谢,
Mats de Waard马茨·德·瓦尔德

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM