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

标签 javascript php jquery json ajax

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

这是我的 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");
    }
});
}

这是我的 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);
}

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

提前致谢,
马茨·德瓦尔德

最佳答案

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

关于javascript - PHP 将 JSON 对象返回给 Javascript [AJAX CALL] 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36352501/

相关文章:

javascript - event.preventDefault() 在 Mozilla 或 IE 中不起作用

javascript - jquery.width 在图像上返回 0

php - CI_Model 中的 $db 在哪里?

javascript - 在没有位置 : absolute 的元素上使用 jQuery .animate()

javascript - 仪表板中可编辑的图片和文本

JavaScript 设置丢失的引用但不改变大小

javascript - 动态添加、验证和删除表单字段集

php - 防止 Web 应用程序中的同时事务

PHP PDO 交易?

javascript - 在 Bootstrap 中悬停打开折叠选项卡