Returning Data From Server To Page Using Ajax
I wanted to know if I can pass back individual parameters from a php script to be stored in dfferent JS variables on the page I'm working on, while also returning generated html code from the php script along with those parameters.
Basically I would like to return some data like this from php using ajax:
$valid = "true";
$access = "false";
$htmlcontent="lorem ipsum<br/>some more text<b>bold</b>";
And all of this should go into equivalent javascript variables on my page,开发者_StackOverflow中文版 using ajax, so that I can contruct my response on the page using this data...
Add the data to an array and json_encode
then:
$ret = array();
$ret["valid"] = "true";
$ret["access"] = "false";
$ret["htmlcontent"] ="lorem ipsum<br/>some more text<b>bold</b>";
echo json_encode($ret);
And in your client side:
$.ajax({
url:"your_script.php",
success:function(resp) {
var json = jQuery.parseJSON(resp)
alert(json.valid)
}
})
Just let PHP print them directly as JS variables. It also saves your client one HTTP request.
<script>
var valid = <?= $valid ?>;
var access = <?= $access ?>;
var htmlcontent = <?= json_encode($htmlcontent) ?>;
</script>
精彩评论