我之前曾进行过 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/