什么因素会导致jquery.ajax每次都将响应视为错误

时间:2017-05-16 00:29:19

标签: javascript jquery json ajax

前端:

<script type="text/javascript">
jQuery("#FormButtonRun").click(function(event){
    submitEmailForm();
});

var submitEmailForm = function ()  {
    var submitdata = {'Email':jQuery('#FormEmail').val(), 'fName':jQuery('#FormName1').val(), 'lName':jQuery('#FormName2').val(), 'listnews':"Yes"};

    jQuery.ajax({
        type:'POST',
        url:'https://dev.formserver.com/ajax.php',
        data:submitdata,
        success: submitwrkd,
        error: submitfaild,
        dataType:'json'
    });
}

var submitwrkd = function(response, more, xhr){
    alert("It worked!);
    alert(response.msg);
}

var submitfaild = function(response, more, xhr){
    alert("allegedly that failed");
}

后端:ajax.php:

<?php
header('Content-type:application/json');
echo json_encode(array('success'=>true, 'msg'=>'It was a success'));
?>

Content-Control-Allow-Origin在内容服务器和发布到服务器上都设置为*

完整标题:

POST /ajax.php HTTP/1.1
Host: dev.dataserver.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: https://dev.dataserver.org/popuptest
Content-Length: 127
Origin: https://dev.contentserver.org
Connection: keep-alive
Email={removed post data}

响应:

HTTP/1.1 200 OK
Server: nginx/1.8.1
Date: Tue, 16 May 2017 00:44:49 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST

数据:{"success":true,"msg":"It was a success"}

Developer tools Network

  • 该按钮成功触发提交
  • 目标服务器日志文件显示请求和响应"POST /ajax.php HTTP/1.1" 200 67 "-" "Mozilla/5.0 ...
  • 浏览器开发工具显示响应:http代码:200,响应内容被识别为json:success: true, msg: 'It was a success'

javascript警告宣布:allegedly that failed

我已经检查了内容控件头Access-Control-Allow-Origin: *; Access-Control-Allow-Methods: POST;,显然它经历了,数据类型,json错误,javascript错误(没有抛出),不同的浏览器......

如何在成功时运行定义的success函数,并在出现错误时运行错误函数?

我可以回到.done(),但我们强烈希望知道它有效。

1 个答案:

答案 0 :(得分:0)

  • 无效的ajax调用参数
  • 在目标服务器或原始服务器上缺少Access-Control-Allow-Origin标头
  • 目标或来源上的Access-Control标头不正确
  • 已损坏的标头(例如:无效的域名/来源名称或Access-Control-Allow-Origin: '*
  • 来自目标服务器的无效响应标头或内容流
  • 禁止源域或目标域
  • Javascipt从第3台服务器加载,CDN(CDN要求设置域标头,目标服务器设置为CDN作为源)
  • 使用过时的ajax框架(较旧的jquery,scriptaculous或prototype),与当前的浏览器无法正常工作Access-Control