Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无法从jquery ajax()请求中读取json对象_Php_Jquery_Ajax - Fatal编程技术网

Php 无法从jquery ajax()请求中读取json对象

Php 无法从jquery ajax()请求中读取json对象,php,jquery,ajax,Php,Jquery,Ajax,我已经浏览了好几次了,但找不到适合我的答案,不管怎样,这里是JS: jQuery.ajax({ url:'scripts/form.php?'+ 'name='+$('#name').val()+ '&comment='+$('#comment').val(), type:'POST', dataType:'json', complete:function(success) { alert(success.

我已经浏览了好几次了,但找不到适合我的答案,不管怎样,这里是JS:

jQuery.ajax({
    url:'scripts/form.php?'+
        'name='+$('#name').val()+
        '&comment='+$('#comment').val(),
    type:'POST',
    dataType:'json',
    complete:function(success) { 
        alert(success.responseText);
        alert(success.name);
    }
});
下面是正在编写的(摘要)脚本

header('Content-type: application/json');
$name    = $_GET['name'];
$comment = $_GET['comment'];

echo json_encode(array('name'=>$name, 'comment'=>$comment));
以下是警报框的输出:

  • {“名称”:“测试名称”,“注释”:“测试注释”}
  • 未定义

  • 我尝试了很多不同的方法,但我不知所措。

    您应该使用
    success
    事件,而不是
    complete
    事件——否则,响应不会自动解析为JSON

    jQuery.ajax({
        url:'scripts/form.php?'+
            'name='+$('#name').val()+
            '&comment='+$('#comment').val(),
        type:'POST',
        dataType:'json',
        success:function(data) { 
            alert(data.name);
        }
    });
    
    如果要使用
    complete
    处理程序,则需要先解析返回值,然后才能将其用作对象:

    var response = $.parseJSON(success.responseText);
    
    使用,因为您不需要使用
    $.ajax()
    的全部灵活性


    我不知道为什么我在问之前为此奋斗了一天。谢谢我看不出有什么理由在这里发布请求-数据在URL参数中。@Matt:这是一次“万岁”的尝试,目的是让响应按我想要的方式工作。
    $.getJSON('scripts/form.php',
    {
        name: $('#name').val(),
        comment: $('#comment').val()
    }, function (data)
    {
        alert(data.name);
    });