Best way to make JSON out of PHP and display it in my jQuery success case?
I have this code in jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$("input[type=submit]").click(function() {
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else {
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
data: dataString,
success: func开发者_运维问答tion() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
// Here can update the right side of the screen with the newly entered information
alert (dataString);
}
});
}
return false;
});
});
</script>
And I have an AJAX call that I want to make JSON so I can unpack the JSON in the success case of the call to the AJAX.
What I don't understand is how to create the JSON and how to make the front end detect it, and how to unpack it and display it. Any advice with that?
My backend return will be simple. Just a name and description for every item returned.
In add_problem.php
use PHP's json_encode()
on the object/array/scalar you want to return.
In your javascript, use jQuery's .getJSON()
to make your AJAX call. Alternatively, you can use jQuery's .ajax()
function and specify dataType: 'json'
.
Here's documentation on jQuery's .getJSON()
:
http://api.jquery.com/jQuery.getJSON/
and here's some documentation on the PHP json_encode()
function:
http://www.php.net/manual/en/function.json-encode.php
Make an array of what you want to return in php, preferably an associative array but it could be integer indexed and it will work just as well.
$arr = array();
// Fill array with return data with PHP.
$arr['name'] = 'John';
echo json_encode($arr);
That will render your array as output in JSON format, which your jQuery success function will pick up in a parameter. Below, I name the parameter json
but you can name it whatever you like.
...
success: function(json) {
var ob = $.parseJSON(json);
// At this point, ob is a JavaScript object that should look pretty much the same
// as the PHP object you created.
alert(ob.name); // In this example, will alert 'John'
}
...
Also note that $.parseJSON
was not introduced in jQuery until version 1.4.1.
Please see: PHP Manual: json_encode()
精彩评论