AJAX:仅触发错误回调函数

6

我已经声明了successerror回调函数,但是即使状态码为200,它也只会调用错误回调函数。

我还在registry.php中进行了一些其他php文件的curl调用。

这是我尝试过的:

$.ajax({
  type: "POST"
  ,data: {
    action: "blah"
    ,mobileNo: that.mobNo
    ,token: that.key
  }
  ,url: "http://90.8.41.232/localhost/registry.php"
  ,cache: false
  ,dataType: "json"
  ,success: function (response) {
    console.log("success");
  }
  ,error: function () {
    console.log("error");
  }
});

我在文档中读到,我们不必显式调用成功回调函数,希望这是正确的。

有没有想法在状态码为200时调用成功回调函数。

响应 希望这能帮到你,这是我从Chrome控制台复制的,而不是通过console.log()打印出来的。

bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"}      {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()

2
您的代码看起来正确,服务器返回的答案是有效的json吗? - aghidini
你确定 http://90.8.41.232/localhost/registry.php 不是跨域数据访问吗?如果是的话,你可能需要在 registry.php 中提供特定的头部来启用 cors,并且你还需要检查跨域数据访问的 jsonp - Jai
错误函数接受三个参数。查看它们,它们可能会告诉你出了什么问题。JavaScript 错误控制台也可以显示错误信息。您的开发工具的网络选项卡将让您确认是否在响应中得到了 200 OK 状态码,您有检查过吗? - Quentin
是的,我已经检查了所有这些事情 @Quentin - PJ1405
我认为你的服务器响应不是有效的JSON格式...看起来像是两个独立的JSON对象。作为一个实验,尝试移除 dataType: "json" 并在成功回调中使用 $.parseJSON()...我认为你会发现它无法解析。 - Matt Browne
显示剩余3条评论
3个回答

2
正如您所提到的,您正在调用另一个php文件进行curl调用。当您进行curl调用时,必须将curl的响应返回给客户端。因此,为了传输curl调用的返回值,您需要设置选项curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);。 这样可以解决您的问题。希望如此。

2
首先,请检查您收到的真正错误(不确定您是否真的收到了200状态码?)
error: function (err) {
  console.error("error");
  console.log(err);
  console.log(err.stack);
  throw err;
}

请展示我们所需的日志文件。

我已添加了响应对象,状态代码为 200ok - PJ1405
请加上 console.log(err); 这行代码,这样你就能看到抛出的错误详情了。 - Rémi Becheras

-2

我几周前做过这件事,如果我像这样调用它,它对我有效

$.ajax(
{
    type: "POST",
    data: { action: "blah", mobileNo: that.mobNo, token: that.key },
    url: "http://90.8.41.232/localhost/registry.php",
    cache: false,
    dataType: json,
})
.success (function (data, status, jqxhr)
{
    // do your stuff
})
.error (function(x, status, jqxhr) 
{
    // handle your errors
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接