【发布时间】:2009-04-16 12:52:08
【问题描述】:
我正在尝试使用jQuery.post() 函数来检索一些数据。但 我没有输出。
我有一个显示表格的 HTML。单击此表应触发 jQuery.post 事件。
我的脚本文件如下所示:
jQuery(document).ready(function() {
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.
jQuery.post("../functions.php", { storeID: "storeID" },
function(data){
alert(data.name); // To test if I get any output
}, "json");
});
});
我的 PHP 文件如下所示:
<?php
inlcude_once('dal.php');
//Get store data, and ouput it as JSON.
function getStoreInformation($storeID)
{
$storeID = "9";//$_GET["storeID"];
$sl = new storeLocator();
$result = $sl->getStoreData($storeID);
while ($row = mysql_fetch_assoc($result)) {
{
$arr[] = $row;
}
$storeData = json_encode($arr);
echo $storeData; //Output JSON data
}
?>
我测试了 PHP 文件,它以 JSON 格式输出数据。我现在唯一的问题是将此数据返回到我的 javascript。
- 由于javascript位于/js/文件夹中,使用'../'调用php文件是否正确?
- 我认为我没有正确传递 storeID 参数。什么是正确的方法?
- 如何调用 getStoreInformation($storeID) 函数并传递参数? jQuery.com 上的 jQuery 示例有以下行: $.post("test.php", { func: "getNameAndTime" } getNameAndTime 是 test.php 中的函数名吗?
我又进了一步。 我已将代码从函数()内部移到外部。所以现在执行文件时会运行php代码。
我的 js 脚本现在看起来像这样:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data);
}, "text");
});
这会导致一个警报窗口,它将商店数据作为 JSON 格式的字符串输出。 (因为我把“json”改成了“text”)。
JSON 字符串如下所示:
[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten@brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]
现在,我真正想要的是从 JSON 中输出数据。 所以我会将“text”更改为“json”,将“alert(data)”更改为“alert(data.name)”。 所以现在我的 js 脚本将如下所示:
jQuery('#storeListTable tr').click(function() {
var storeID = this.cells[0].innerHTML;
jQuery.post("get_storeData.php", { sID: storeID },
function(data){
alert(data.name);
}, "json");
});
不幸的是,我得到的唯一输出是“未定义”。 如果我改变“alert(data.name);”到“alert(data);”,输出为“[object Object]”。
那么如何输出店铺名称呢?
在 PHP 文件中,我尝试设置 $storeID = $_GET["sID"];但我不知道价值。如何获取在 jQuery.post 中作为参数传递的值? (目前我已经硬编码了 storeID,用于测试)
【问题讨论】:
标签: php javascript jquery