jQuery JSON问题

Nic*_*erg 3 javascript php ajax jquery json

我想在用户在#sid字段中输入值后立即使用数据库中的值填充表单字段.这是我的jQuery/HTML示例:

<script src="jquery-1.3.1.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function()
{
  $('#sid').bind("change", function(){
    $.getJSON("test.php?sid=" + $("#sid").val(), 
    function(data)
    {
      $.each(data.items, 
      function(i, item)
      {
        if (item.field == "saffil")
        {
              $("#saffil").val(item.value);
        }
        else if (item.field == "sfirst")
        {
              $("#sfirst").val(item.value);
        }
      });
      });
   });
});
</script>
Run Code Online (Sandbox Code Playgroud)

这是我的处理脚本(test.php,由.getJSON方法调用)

<?
require_once("db_pers.inc");

$ssql = "SELECT * FROM contacts_mview WHERE sempid = '".$_GET['sid']."'";

$rres = pg_query($hdb, $ssql);
pg_close($hdb);

$ares = pg_fetch_assoc($rres);

$json = array(array('field' =>  'saffil',
            'value' =>  $ares['saffil']),
          array('field' =>  'sfirst',
            'value' =>  $ares['sfirst']));

echo json_encode($json);
?>
Run Code Online (Sandbox Code Playgroud)

根据firebug,GET param被传递到test.php并且JSON对象恢复正常:

[{"field":"saffil","value":"Admin"},{"field":"sfirst","value":"Nicholas"}]
Run Code Online (Sandbox Code Playgroud)

但是页面上没有任何反应,我收到以下错误消息:

G is undefined
init()()jquery-1....1.min.js (line 12)
(?)()()test.html (line 15)
I()jquery-1....1.min.js (line 19)
F()()jquery-1....1.min.js (line 19)
[Break on this error] (function(){var l=this,g,y=l.jQuery,p=l.....each(function(){o.dequeue(this,E)})}});
Run Code Online (Sandbox Code Playgroud)

这是我用jQuery首次尝试ajax,所以任何输入都会非常感激!

谢谢,

  • 尼古拉斯

Cre*_*esh 7

漂亮的小注射攻击在那里等待;)

尝试改变

$.each(data.items,
Run Code Online (Sandbox Code Playgroud)

至:

$.each(data,
Run Code Online (Sandbox Code Playgroud)

编辑:要回答您的评论,我喜欢将我的字段命名为与数据键相同:

<input type="text" name="saffil" value="" />
<input type="text" name="sfirst" value="" />

var data = {saffil:'foo', sfirst:'bar'};
$.each(data, function(key, value) {
   $('[name='+key+']').val(value)
})
Run Code Online (Sandbox Code Playgroud)