开发者

How to receive and use a json in ajax sended from php? [closed]

开发者 https://www.devze.com 2023-01-28 09:50 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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

精彩评论

暂无评论...
验证码 换一张
取 消