Jquery ajax成功函数没有执行?

时间:2014-04-24 07:30:43

标签: javascript php jquery ajax json

Jquery ajax成功函数没有执行?

JSON

这是/controll/operation.php?p=demo

的json输出
{"message-count":"1","messages":[{"to":"3321313","status":"6","error-text":"Unroutable message - rejected","network":"MV-FIXED"}]}

这是从jason验证器检查的有效json。

javascript代码

$('#send').click(function()
           {
       var to = $('#to').val();
       var sender = $('#sender').val();
       var message = $('#message').val();
       if (to == "") {
       $("#forto").addClass("has-error");
            return false;
            }
       if (sender == "") {
            $("#forsender").addClass("has-error");
            return false;
            }
        if (message == "") {
             $("#formessage").addClass("has-error");
            return false;
            }
        $("#send").prop( "disabled", true );
        $("#alert").html('<img style="display:block;margin:0 auto 0 auto;" src="../images/loading.gif">');

            $.ajax("../controll/operation.php?p=demo", {
                type: "POST",
                async: true,
                dataType: "json",
                data: { "to": to, "sender": sender, "message": message},
                success: function (response) {

                var table = '<div align="center">';

                    for (var i = 0; i < response.messages.length; i++)
                    {
                        var status = response.messages[i].status;
                        var to = response.messages[i].to;
                        var messageprice = response.messages[i].messageprice;
                        var remainingbalance = response.messages[i].remainingbalance;
                        var errortext = response.messages[i].errortext;

                        if(status == "0")
                        {
                            status = "Message sent successfully to ";
                        }
                        else
                        {
                            status = errortext;
                        }
                        table = table + '<p>'+status+to+'</p>';

                    }

                    table = table + '</div>';

                    $("#alert").html(table);
                    $("#send").prop( "disabled", false);

                },
        error: function (header, status, error) {
                console.log('ERROR' + header + ' ' + status + ' ' + error);
            }
            });

});

浏览器控制台输出

ERROR[object Object] parsererror SyntaxError: Unexpected end of input 

1 个答案:

答案 0 :(得分:0)

您需要将响应文本解析为JSON对象。请参阅以下示例。

var jsonData = '{"message-count":"1","messages":[{"to":"3321313","status":"6","error-text":"Unroutable message - rejected","network":"MV-FIXED"}]}';

var data = $.parseJSON(jsonData);
$.each(data.messages, function(i, item) {
    alert(item.to);
    alert(item.status);
});

但是,error-text未被访问,因为它包含一个特殊字符。最好将其从服务器端重命名为errortext;