jQuery ajax POST总是返回错误

时间:2014-08-22 08:14:45

标签: jquery ajax

这是我的jQuery ajax函数

<html>
    <head>
        <script src="jquery-1.11.1.min.js"></script>
    </head>
    <body>
    <script>
    jQuery(document).ready(function($) {
        $.ajax({
            url: 'MY_CGI_SERVER/cgi-bin/test.cgi',
            type: 'POST',
            data: '{"type": "appStore","command": "GET","user": "John","passwd": "123456","deviceID": "123456789","count": "0","page": "1", "content": "basic","sortBy": "rate","byAppID": "false","appIDList": ""}',
            success: function(response){
                alert("OK!\n");
            },
            error: function(xhr, status, error){
                alert(xhr);
            }
        });
    });
    </script>
    </body>
</html>

它总是返回错误函数,但我使用wireshark来捕获包, 数据发布成功,也是回复。

包裹如下:

enter link description here

有什么问题?

2 个答案:

答案 0 :(得分:0)

首先删除数据值周围的单引号

   jQuery(document).ready(function($) {
        $.ajax({
            url: 'MY_CGI_SERVER/cgi-bin/test.cgi',
            type: 'POST',
            data: {"type": "appStore","command": "GET","user": "John","passwd": "123456","deviceID": "123456789","count": "0","page": "1", "content": "basic","sortBy": "rate","byAppID": "false","appIDList": ""},
            success: function(response){
                alert("OK!\n");
            },
            error: function(xhr, status, error){
                alert(xhr);
            }
        });
    });

如果您仍然遇到问题,则会触发错误,因为您的cgi输出或打印json字符串两次或者某些nonjson,这与json的语法冲突。始终输出单行或至少通过连接

来维护语法

检查您的错误函数是输出有效的json数据还是稍微输出

遍历所有xhr

$.each(xhr, function(key, value) {
  alert(key + ": " + value);
});

答案 1 :(得分:0)

我的服务器端是Perl编程。

因为ajax总是转到错误函数,所以我硬编码响应数据。

这是我的响应服务器端代码。

sub SendResponse()
{
    $response = shift;

    print header('application/json; charset=utf-8');
    print '{"test":"123","123":"test"}';
}