[英]Ajax Call From PHP File TO a PHP File
这是我在我的php文件中执行的ajax调用:
$.ajax({
type: "POST",
url: "../includes/filters.php",
data: {"email" : email},
dataType: "json",
success: function(data)
{
if(data.equals('sent'))
{
alert(data);
}
else
{
alert("There Was Some Problem Please Try Again!");
}
},
error: function(xhr, status, text) {
console.log(xhr);
console.log(status);
console.log(text);
}
});
这是filters.php文件:
$email = $_POST['email'];
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$query = "---------some query------";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$temp = $stmt->num_rows;
if ($temp == 1)
return json_encode('true');
else
return json_encode('false');
这是我在安慰中得到的错误
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}
(index):120 parsererror
(index):121 SyntaxError: Unexpected end of input
at Object.parse (native)
at n.parseJSON (http://localhost/pedagoge/assets/plugins/jquery/jquery-2.1.4.min.js:4:5497)
at ub (http://localhost/pedagoge/assets/plugins/jquery/jquery-2.1.4.min.js:4:7521)
at x (http://localhost/pedagoge/assets/plugins/jquery/jquery-2.1.4.min.js:4:10935)
at XMLHttpRequest.n.ajaxTransport.k.cors.a.crossDomain.send.b (http://localhost/pedagoge/assets/plugins/jquery/jquery-2.1.4.min.js:4:14765)
请帮帮我,因为我已经尝试了所有的JSON转换,所以我什至尝试转换其中带有字符串的php变量,没有任何线索
您需要echo
显JSON响应,而不return
它。
echo json_encode($temp == 1 ? 'true' : 'false');
另外,您的Javascript代码期望响应成功时sent
,而不是true
或false
。
在Javascript中,您将==
而不是.equals()
:
if (data == "sent")
没有来自filters.php
输出; 您需要echo
而不是return
。
不使用JSON:
$email = $_POST['email'];
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$query = "---------some query------";
$stmt = $mysqli->prepare($query); // XXX $mysqli is not initialized
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows == 1 ? "sent" : "not-sent";
我非常确定您的json_encode('true');
的结果json_encode('true');
实际上并不构成有效的JSON,您已在ajax调用中将其指定为期望返回结果的dataType
,这就是为什么会出现解析错误的原因。
echo json_encode('true');
给
"true"
任何想象力都不是json字符串。
试试这个
$result = array();
$result['status'] = 'not sent';
if ($temp == 1) {
$result['status'] = 'sent';
}
echo json_encode($result);
现在在您的javascript成功函数中
success: function(data)
{
if(data.status == 'sent') {
alert(data.status);
} else {
alert("There Was Some Problem Please Try Again!");
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.