How to return values from an ajax call along with HTML result?
I've my jquery code as
$(function() {
$("#addline").click(function() {
$.a开发者_JS百科jax({
type: "POST",
url: "proc/add-line.php",
data: // some string,
cache: false,
success: function(html){
$("ul#nextLines").append(html);
if(lineId == 10) { // lineId value to be passed from add-line.php
$("#addForm").hide();
}
}
});
}return false;
});
});
In the line commented as "// lineId to be passed from add-line.php" [refer to code above], I want the php processing page add-line.php to pass the value of the var lineId.
At present, the add-line.php gives out a html code <li><?php echo $line; ?></li>
. Along with that, I want to send the value of the lineId so that I can implement that conditioning.
So how should I send and then retrieve the value of the lineId (retrieved in the form of a PHP variable) from add-line.php??
Update
I've made changes to my code above as
$.ajax({
type: "POST",
url: "proc/add-line.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
alert(data.html);
$("ul#nextLines").append(data.html);
$("ul#nextLines li:last").fadeIn("slow");
$("#flash").hide();
if(data.lineId == 10) {
$("#addForm").hide();
}
}
});
And PHP code is
// Header type
header('Content-Type: application/json; charset=utf-8');
$data = array(
"html"=> "test",
"lineId" => "1"
);
echo json_encode($data);
I've not been able to retrieve the json. (even the alert(data.html)
in the success function call doesn't show up).
Can you help me figure this out?? Thanks.
One option would be to return JSON with json_encode
:
$data = array('html'=> "<li>$line</li>",
'lineId' => $lineId //wherever that comes from
);
echo json_encode($data);
JavaScript:
$.ajax({
type: "POST",
url: "proc/add-line.php",
data: // some string,
dataType: 'json',
cache: false,
success: function(data){
$("ul#nextLines").append(data.html);
if(data.lineId == 10) {
$("#addForm").hide();
}
}
});
Two solutions:
Either return JSON from your PHP script:
// In PHP:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array(
'html' => '<li>' . intval($lineId) . '</li>',
'lineId' => $lineId,
));
// In JS:
success: function(json){
var lineId = json.lineId;
var html = json.html;
// ...
}
Due to the Content-Type header being set to application/json, jQuery will automatically parse the result as JSON. So the first parameter of the success callback is the parsed JSON object.
Or return the lineId in a HTTP header:
// In PHP
header('X-LineId: ' . $lineId);
// In JS
success: function(html, textStatus, xhr){
var lineId = xhr.getResponseHeader('X-LineId');
// ...
}
精彩评论