douya2007
douya2007
2012-01-19 14:00

.getJSON .each()不解析JSON数据[关闭]

已采纳

I am querying a PHP page (not on an external site) using $.getJSON which will return a MySQL result set, I have used json_encode() to format the result set to a JSON string. The problem is I get the data back but when I try to set the values of some hidden fields nothing happens. I had this working but now it's not. I must have changed something without realizing it. Here's the code:

jQuery:

$.getJSON('includes/Lookup.php', {locationType:$('#location').val()}, function(data) {

var valA = $('#valA');
var valB = $('#valB');
var valC = $('#valC');

$.each(data, function(index, data) {
     valA.val(data.field_valueA);
     valB.val(data.field_valueB);
     valC.val(data.field_valueC);
 });
});

Lookup.php:

<?php
$db = new MySqlDB();

if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {

if(isset($_GET['locationType'])){

    $locationType = $_GET['locationType'];
    $db->where('id', $locationType);

    $sql = "SELECT field_valueA, field_valueB, field_valueC FROM table";
    $results = $db->query($sql);

    echo json_encode($results);

} else {
    echo 'not set';
}
}

This is what I get in Firebug:

<??> {"field_valueA":2,"field_valueB":3.12,"field_valueC":12345}

I don't know why <??> is included. I am doing this exact call in two different places, on two different tables (neither are working) this is what I am getting from the other call:

<??> [{"field_valueA":905,"field_valueB":18.180000305176,"field_valueC":16453}]

If anyone has an idea as to what is going on I'd appreciate it.

EDIT: Now it seems as if ALL my ajax responses throughout my application are being prefixed with <??>. They all worked before and now they are not, I have no idea what is going on.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • du5591 du5591 9年前

    Solved! I am embarrassed to say that I had a typo in my code, it's very easy to miss an extra <?. Thanks for your suggestions.

    点赞 评论 复制链接分享
  • dongwo6477 dongwo6477 9年前

    why dont you simply do

     valA.val(data.field_valueA);
     valB.val(data.field_valueB);
     valC.val(data.field_valueC);
    

    no need to iterate in your case

    点赞 评论 复制链接分享
  • doukan3504 doukan3504 9年前

    Your PHP seems to miss the closing php tag ?> in the end. Maybe that's why it's acting weird ...

    点赞 评论 复制链接分享

相关推荐