How to receive and use a json in ajax sended from php? [closed]
I want to receive json from开发者_如何学运维 php to ajax and want to access the different field values in json.
On the PHP side, use json_encode()
to convert your data to JSON, and write it out, then exit. Best send a content type header first, to make sure the receiving end recognizes it as JSON:
<?php
$response_data = whatever_function();
$response = json_encode($response_data);
header("Content-type: text/json");
echo $response;
exit;
On the client, your best bet is to use an existing AJAX framework, such as the AJAX functionality built into jQuery. Suppose your script is at http://example.com/ajax.php
, and the client page is at http://example.com/ajaxclient.html
, a suitable piece of jQuery would go something like:
$.getJSON('ajax.php', { /* GET data goes here */ }, function(data) {
/* data contains the values you sent in your PHP script */
});
In jQuery it will be implementing something like this:
var user = {};
$.ajax({
url: 'http://mysite.com/api/user.json',
data: {'id': '42'},
success: function(data){user = data;},
});
$('#name').val(user.name);
$('#email').val(user.email);
精彩评论