Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/274.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创建JSON数据并使用jQuery进行解析_Php_Ajax_Json - Fatal编程技术网

使用PHP创建JSON数据并使用jQuery进行解析

使用PHP创建JSON数据并使用jQuery进行解析,php,ajax,json,Php,Ajax,Json,我正在使用PHP脚本创建JSON数据。看起来是这样的: {"Id":0} 现在,如果我把它放到一个文件中,然后使用ajax加载它,就可以了。但是如果我从PHP脚本中请求,我会得到 parsererror | SyntaxeError:意外标记非法 下面是我用来从PHP加载JSON的代码: $.ajax({ url: 'check.php', data: { usern

我正在使用PHP脚本创建JSON数据。看起来是这样的:

{"Id":0}
现在,如果我把它放到一个文件中,然后使用ajax加载它,就可以了。但是如果我从PHP脚本中请求,我会得到

parsererror | SyntaxeError:意外标记非法

下面是我用来从PHP加载JSON的代码:

$.ajax({
                    url: 'check.php',
                    data: {
                        username: 'LOL',
                        password: '1234'
                    },
                    dataType: 'json',
                    type: 'POST',
                    success: function(data) {
                        $('#result').html('#Id=' + data.Id);
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        $('#result').html(textStatus + ' | ' + errorThrown);
                    }
                });
以下是PHP代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php

    echo '{"Id":0}';

?>


有什么想法吗?

doctype属于HTML文档,而不是JSON

在PHP文件中尝试类似的方法(仅此)


在错误函数中,使用此函数并检查从服务器返回的数据

error: function(jqXHR, textStatus, errorThrown) {
   $('#result').html(textStatus + ' | ' + errorThrown + ' | ' + jqXHR.responseText);
   alert(jqXHR.responseText);
}
你会知道到底哪里出了问题。数据类型和特殊字符。将内容类型设置为application/json,并使用
json\u encode()
对json字符串进行编码。另外,您不需要doctype。

使用jquery的parseJSON
e、 g


您是如何从PHP请求的?@Pradeep:Edit done@ultimatebuster:Yes我知道谢谢PHP错误消息通常会声明文件并在错误行中加上一行occurred@Joaqu正如您所评论的,ín添加了一个示例:),这将导致更多错误,因为他的选项中包含
dataType:'json'
<代码>数据已被解析(或未能解析,在这种情况下,parseJSON将再次失败)。
<?php
header('Content-Type: application/json');
$data = array(
    'Id'  => 0,
    'foo' => $someOtherComplexVariable
);
echo json_encode($data);
exit;
error: function(jqXHR, textStatus, errorThrown) {
   $('#result').html(textStatus + ' | ' + errorThrown + ' | ' + jqXHR.responseText);
   alert(jqXHR.responseText);
}
success: function(data) {
    data = jQuery.parseJSON(data);
 $('#result').html('#Id=' + data.Id);
}