2012-03-14 94 views
0

我试图让jQuery检索PHP变量并将它们插入到输入值中。我无处不在寻找解决方案。jQuery没有从PHP脚本接收JSON编码的数据

这是jQuery代码。

$(document).ready() { 
$(function() { 
    $.ajax({ 
     type: 'POST', 
     url: 'loadstuff.php', 
     data: { 
      'something': something, 
      'different': different, 
      'another': another 
      }, 
     dataType: 'json', 
     success: function(data) { 
     $('input[name=get_seomething_here]').val('something'); 
     $('input[name=get_different_here]').val('different'); 
     $('input[name=get_another_here]').val('another'); 
} 
    }); 

}); 
}); 

而这里是PHP方面。

//connecting to db etc. 

$query = "SELECT something, different, another FROM stuff WHERE id='1'"; 
$result = mysql_query($query) or die(mysql_error()); 
$row = mysql_fetch_array($result); 

echo(json_encode(array('something' => $row['something'], 
'different' => $row['different'], 
'another' => $row['another'] 
))); 
+0

你有没有尝试设置标题为text/json?在你的PHP回声之前,把:header('Content-type:text/json'); – kingcoyote 2012-03-14 17:48:44

+1

@kingcoyote适用于json的'Content-type'是'application/json';所以它应该看起来像'header('Content-type:application/json');' – Edwin 2012-03-14 18:13:19

+0

要记住的另一件事是强制'JSON_NUMBERIC_CHECK',否则所有的PHP数字都将被转换为JavaScript字符串类型。如果你正在查询的列不包含数字,你不必担心,但你应该这样做,因为这是一个好习惯。 – Edwin 2012-03-14 18:15:09

回答

2

我觉得应该是:

$('input[name=get_seomething_here]').val(data.something); 
$('input[name=get_different_here]').val(data.different); 
$('input[name=get_another_here]').val(data.another); 
+0

谢谢你的回应。我改变了你的建议后的代码。但是,由于某些原因,数据仍然无法通过... – user1269386 2012-03-14 20:47:42

-1

aletzo是正确的..但这样做,你必须做像以前一样:

data = eval("(" + data + ")"); 

然后你可以使用data.something, data.different和data.another

+0

我一直在做这件事,而且'eval()'不仅是不必要的,而且可以让Web应用程序容易受到XSS攻击。 – Edwin 2012-03-14 18:11:53

+0

可以使用JSON.parse而不是eval – Smit 2012-03-14 18:13:33

+0

尽管如此,在不必要时调用额外的方法效率不高。 – Edwin 2012-03-14 18:16:05