Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

ajax - Creating JSON data using PHP and parsing it using jQuery

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

{"Id":0}

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 | SyntaxError: Unexpected token ILLEGAL

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);
                    }
                });

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}';

?>

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Doctypes belong on HTML documents, not JSON.

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

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

Given what you have posted, I can't see any reason to even involve PHP. I'm guessing you've only posted a very simple example. Should it become more complex, involving server-side processing, data retrieval, etc, use PHP's json_encode(), for example

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...