Jquery working with literal value, but not my PHP returned JSON data from $.post
I'm using jQuery's $.post to get values from a query and (trying to) populate a form with those values. The populate plugin needs a JSON object. To test my success callback, I alert and display the data - which looks like valid JSON to me, but the plugin doesn't load the form field. However, if I substitute a literal value e.g. {"cust_id": "65"}, it works. What's the issue? Thanks.
.....here's the cli开发者_运维技巧ent side:
<script type="text/javascript">
$(".button").click(function () {
var suite = $("input#suite_no").val();
$.post("get_custrec.php",
{ suite_no: suite },
function(data){
data = data.substring(1, data.length-1);
$('#output').html(data);
alert("Data: " + data);
$('#custForm').populate(data);
}
);
return false;
});
</script>
.......my server (php) code:
$result = mysql_query($sql);
$arr = array();
while($obj = mysql_fetch_object($result)) {
$arr[] = $obj;
}
echo json_encode($arr);
$.post("get_custrec.php",
{ suite_no: suite },
function(data){
data = data.substring(1, data.length-1);
$('#output').html(data);
alert("Data: " + data);
$('#custForm').populate(data);
}, 'json' //just need to add this ;)
);
If you don't specify the dataType
that will be returned, jQuery tries to guess it by looking at the response's MIME type (e.g. the HTTP Content-Type
header). Since it doesn't look like you're setting the header, you need to:
- set the correct HTTP header:
header("Content-Type: application/json");
and/or tell jQuery what the dataType is, with one more argument to
$.post()
:$.post('get_custrec.php', {...}, function (data) {...}, 'json')
Either one will suffice; using both will not hurt.
精彩评论