0

这就是我想做的。用户提交表单(单个文本输入)并发送到 PHP。PHP 返回这个;

{"status":"true","custid":"00001","custname":"John"}

我知道它是 JSON 格式,但我不知道如何捕获和使用该值,因此我可以使用返回的值。

$(function(){
$('#icnumber-form').submit(function(){       

    var icno  = $('#icnumber').val();
    var purl  = 'php/create_process.php'

    $.ajax({
        type    : 'POST',
        url     : purl,
        cache   : false,
        data    : icno,
        dataType: 'json',
        success : function(response){
            var json = $.parseJSON(response);
            alert(json.message);
        },           
        beforeSend:function(){
            $('.cust-exist-view').show();
            }
    });
    return false;

})
});
4

2 回答 2

1

由于您将 dataType 设置为json,因此响应作为已解析的对象返回,因此您不要尝试自己解析它。

    success : function(response){
        alert(response.status);
    },               
于 2013-07-22T03:57:09.423 回答
0

您不需要使用 varjson = $.parseJSON(response);因为 jQuery 会自动将 JSON 字符串解析为 object 。只需将其用作 javascript 对象即可访问 json 属性。我从您的代码创建了一个简单的演示。在 jsfiddle 中查看

JS代码:

$(function () {
    $('#icnumber-form').submit(function () {

        //var icno = $('#icnumber').val();
        var purl = '/echo/json/'

        $.ajax({
            type: 'POST',
            url: purl,
            cache: false,
            data: {
                json: '{"status":"true","custid":"00001","custname":"John"}',
                delay: 1
            },
            dataType: 'json',
            success: function (response) {
                alert( "status:" + response.status
                      + "\ncustname:"+response.custname
                      + "\ncustid:"+ response.custid);
            },
            beforeSend: function () {
                // $('.cust-exist-view').show();
            }
        });
        return false;

    })
});


所以你只需要查看这部分来了解如何使用 json return :

success: function (response) {
                alert( "status:" + response.status //access status
                      + "\ncustname:"+response.custname //access custname
                      + "\ncustid:"+ response.custid); // access custid
            },
于 2013-07-22T04:12:26.990 回答