2012-03-29 83 views
1

我使用php与mysql数据库交谈,然后用json_encode编码关联数组。我知道的很多工作,我可以直接调用php并查看json结果。jQuery Json + jQuery onChange

使用jQuery我在下拉菜单上使用onChange来调用php函数并获取结果。

我认为我有jQuery和json的问题,但我已经浏览了多个帖子,找不到一个好的答案。

这是我使用的代码。我如何到达json数组?我已经尝试过数据['ele'],data.ele,data [0],所有的返回值都是未定义的。

$('#itemDD').change(function(data){ 
     alert("Changing"); 
     askServer(function(data){ 
     alert("!" + data['retailListPrice']); 
     //spin through the data and put the results in workingQuote 
     }); 
    }); 

function askServer(callback) 
{ 
    var selItem = $('#itemDD').val(); 
    var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo"; 
    alert(strUrl); 
    jQuery.ajax({ 
     url:strUrl, 
     success:callback, 
     dataType: "json" 
    }); 
} 

}); 

PHP

$sql="SELECT * 
       FROM items 
       WHERE modelNum='" . $selectedModel . "'"; 
     $result = mysql_query($sql,$conn) or die("Error" . mysql_error()); 

     while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray)); 
     echo json_encode($resultArray); 
+0

确保您提供的网址OK,尽量绝对URL,如“http://example.com /getItemList.php?item=“+ selItem +”&动作= itemInfo“与”http://“ – 2012-03-29 02:40:59

+0

我给了它完整的网址,而且什么也没有。我正在更新与PHP。 – 2012-03-29 02:46:37

回答

1

您使用数组和mysql_fetch_assoc。因此,要获得的数据,使用数据[0] [ 'rowName']数据[0] .rowName

1

试试这个(注:对象/数组格式是不同势在JS):

function askServer() 
{ 
    var selItem = $('#itemDD').val(); 
    var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo"; 
    alert(strUrl); 
    $.get(strUrl, function(data){ 
     alert(data.retailListPrice); 
    }); 
} 
+0

我仍然未定义。我将askServer函数中的代码放入#itemdd – 2012-03-29 02:38:37

+0

的更改函数中,发布您的json字符串。 (你是否在php端设置了json头文件..不是必须的,但有时候会有帮助) – Rufinus 2012-03-29 02:51:44

+0

如果你使用萤火虫或其他控制台感知的开发者工具,你也可以尝试'console.dir(data)' – Rufinus 2012-03-29 02:52:40

1

内改变事件只是调用askServer()功能,并宣布它的外变更事件,如

$('#itemDD').change(function(data){ 
    //... 
    askServer(); 
}); 

和你askServer()功能

function askServer() 
{ 
     var selItem = $('#itemDD').val(); 
     var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo"; 
     $.get(strUrl, function(data){ 
      $.parseJSON(data); 
      alert(data.retailListPrice); 
     }); 
}