使用PHP创建JSON数据,并使用jQuery解析它 [英] Creating JSON data using PHP and parsing it using jQuery

查看:111
本文介绍了使用PHP创建JSON数据,并使用jQuery解析它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a PHP script to create JSON data. It looks like this:

{"Id":0}

现在,如果我将它放入一个文件,然后用ajax它的罚款加载。但是,如果我要求这从PHP脚本就可以得到

Now if I put that into a file and then load it using ajax it's fine. But if I request this from the PHP script I get

parsererror |语法错误:意外的标记非法

parsererror | SyntaxError: Unexpected token ILLEGAL

下面是我用来加载从PHP的JSON的$​​ C $ C:

Here is the code that I am using to load the JSON from the PHP:

$.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 code:

Here is the PHP code:

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

<?php

    echo '{"Id":0}';

?>

任何想法?

推荐答案

文档类型属于HTML文档上,而不是JSON。

Doctypes belong on HTML documents, not JSON.

尝试像这样在你的PHP文件(仅此)

Try something like this in your PHP file (and only this)

<?php
header('Content-Type: application/json');
?>
{"Id":0}

由于你所发布的,我看不到任何理由,甚至包括PHP。我猜你只发布了一个很简单的例子。如果它变得更加复杂,涉及到服务器端处理,数据检索等,使用PHP的 json_en code(),例如:

<?php
header('Content-Type: application/json');
$data = array(
    'Id'  => 0,
    'foo' => $someOtherComplexVariable
);
echo json_encode($data);
exit;

这篇关于使用PHP创建JSON数据,并使用jQuery解析它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆