无法使用jQuery.post检索数据

时间:2022-11-27 08:03:17

I'm trying to use jQuery.post() function to retrieve some data. But i get no output.

我正在尝试使用jQuery.post()函数来检索一些数据。但我没有输出。

I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.

我有一个显示表格的HTML。单击此表应触发jQuery.post事件。

My scriptfile looks like this:

我的脚本文件如下所示:

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"); 
    }); 
});  

My PHP file looks like this:

我的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 
  } 
?> 

I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.

我测试了PHP文件,它以JSON格式输出数据。我现在唯一的问题是将此数据返回到我的javascript。

  1. since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
  2. 由于javascript位于/ js /文件夹中,使用'../'调用php文件是否正确?

  3. I don't think I'm passing the storeID parameter correctly. What is the right way?
  4. 我不认为我正确传递storeID参数。什么是正确的方法?

  5. How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" } Is the getNameAndTime the name of the function in test.php ?
  6. 如何调用getStoreInformation($ storeID)函数并传递参数? jQuery.com上的jQuery示例包含以下行:$ .post(“test.php”,{func:“getNameAndTime”} getNameAndTime是test.php中函数的名称吗?


I have gotten one step further. I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.

我更进了一步。我已将代码从函数()内部移到外部。所以现在php代码在文件执行时运行。

My js script now looks like this:

我的js脚本现在看起来像这样:

  jQuery('#storeListTable tr').click(function() {
    var storeID = this.cells[0].innerHTML;

    jQuery.post("get_storeData.php", { sID: storeID },
      function(data){
         alert(data);
      }, "text");
    });

This results in an alert window which ouputs the store data as string in JSON format. (because I have changed "json" to "text").

这会生成一个警报窗口,将存储数据输出为JSON格式的字符串。 (因为我已将“json”更改为“text”)。

The JSON string looks like this:

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"}]

Now, what I really want, is to ouput the data from JSON. So I would change "text" to "json" and "alert(data)" to "alert(data.name)". So now my js script will look like this:

现在,我真正想要的是从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");
    });

Unfortunately, the only output I get, is "Undefined". And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".

不幸的是,我得到的唯一输出是“Undefined”。如果我改变“alert(data.name);” “alert(data);”,输出为“[object Object]”。

  1. So how do I output the name of teh store?

    那么如何输出商店的名称?

  2. In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ? (currently I have hardcoded the storeID, for testing)

    在PHP文件中,我尝试设置$ storeID = $ _GET [“sID”];但我不认为这个价值。如何在jQuery.post中获取作为参数传递的值? (目前我已经硬编码了storeID,用于测试)

4 个解决方案

#1


Lose the quotes around "storeID":

丢失“storeID”周围的引号:

Wrong:

jQuery.post("../functions.php", { storeID: "storeID" }

jQuery.post(“../ functions.php”,{storeID:“storeID”}

Right:

jQuery.post("../functions.php", { storeID: storeID }

jQuery.post(“../ functions.php”,{storeID:storeID}

#2


bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.

bartclaeys是正确的。就像现在一样,您实际上是将字符串“storeID”作为商店ID传递。

However, a couple more notes:

但是,还有几个笔记:

  • It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
  • 您将设置storeID可能看起来很奇怪:storeID - 为什么只有第二个被评估?当我第一次开始时,每次我不发送“1:1”或其他东西时我都要三重检查。但是,当您使用这样的对象表示法时,不会计算键,因此只有第二个键将是实际的变量值。

  • No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
  • 不,您将PHP文件称为../考虑JS文件的位置是不正确的。您必须根据加载此javascript的任何页面调用它。因此,如果页面实际上与您调用的PHP文件位于同一目录中,则可能需要将其修复为指向正确的位置。

  • Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
  • 有点像以前的点,你真的想要得到Firebug。这将允许您在发送AJAX请求时,如果它们成功发出,发送给它们的数据以及正在发回的数据,则会看到它们。简而言之,它是调试Javascript / AJAX应用程序的首选共识工具,你应该拥有它,使用它,并且如果你不想浪费另外6天来调试一个愚蠢的错误,就要珍惜它。 :)

EDIT As far as your reply, if you break down what you are returning:

编辑就你的回复而言,如果你打破了你的回归:

[
  {
    "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"
  }
]

This is actually an array (the square brackets) containing a single object (the curly braces).

这实际上是一个包含单个对象(花括号)的数组(方括号)。

So when you try doing:

所以当你尝试做:

alert(data.name);

This is not correct because the object resides as the first element of the array.

这是不正确的,因为该对象作为数组的第一个元素。

alert(data[0].name);

Should work as you expect.

应该像你期望的那样工作。

#3


Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]

你的JSON作为一个javascript数组返回...用[]包装卷曲位[{}]

so this would work.

所以这会奏效。

wrong:  alert(data.name);
right:  alert(data[0].name);

Hope that helps. D

希望有所帮助。 d

#4


Ok, thanks to Darryl, I found the answer.

好的,多亏了Darryl,我找到了答案。

So here is the functional code for anyone who is wondering about this:

所以这里是任何想知道这个问题的人的功能代码:

javascript file

jQuery(document).ready(function() {

  jQuery('#storeListTable tr').click(function() {

    jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML },     // this.cells[0].innerHTML is the content ofthe first cell in selected table row
      function(data){
         alert(data[0].name);
      }, "json");
    });

});

get_storeData.php

<?php
  include_once('dal.php');

  $storeID = $_POST['storeID'];   //Get storeID from jQuery.post parameter

  $sl = new storeLocator();
  $result = $sl->getStoreData($storeID);  //returns dataset from MySQL (SELECT * from MyTale)

  while ($row = mysql_fetch_array($result))
  {
    $data[] = array( 
    "id"=>($row['id']) ,
    "name"=>($row['name']));
  }  

  $storeData = json_encode($data);

  echo $storeData;
?>

Thanks for all your help guys!

谢谢你们的帮助!

#1


Lose the quotes around "storeID":

丢失“storeID”周围的引号:

Wrong:

jQuery.post("../functions.php", { storeID: "storeID" }

jQuery.post(“../ functions.php”,{storeID:“storeID”}

Right:

jQuery.post("../functions.php", { storeID: storeID }

jQuery.post(“../ functions.php”,{storeID:storeID}

#2


bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.

bartclaeys是正确的。就像现在一样,您实际上是将字符串“storeID”作为商店ID传递。

However, a couple more notes:

但是,还有几个笔记:

  • It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
  • 您将设置storeID可能看起来很奇怪:storeID - 为什么只有第二个被评估?当我第一次开始时,每次我不发送“1:1”或其他东西时我都要三重检查。但是,当您使用这样的对象表示法时,不会计算键,因此只有第二个键将是实际的变量值。

  • No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
  • 不,您将PHP文件称为../考虑JS文件的位置是不正确的。您必须根据加载此javascript的任何页面调用它。因此,如果页面实际上与您调用的PHP文件位于同一目录中,则可能需要将其修复为指向正确的位置。

  • Kind of tied to the previous points, you really want to get your hands on Firebug. This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)
  • 有点像以前的点,你真的想要得到Firebug。这将允许您在发送AJAX请求时,如果它们成功发出,发送给它们的数据以及正在发回的数据,则会看到它们。简而言之,它是调试Javascript / AJAX应用程序的首选共识工具,你应该拥有它,使用它,并且如果你不想浪费另外6天来调试一个愚蠢的错误,就要珍惜它。 :)

EDIT As far as your reply, if you break down what you are returning:

编辑就你的回复而言,如果你打破了你的回归:

[
  {
    "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"
  }
]

This is actually an array (the square brackets) containing a single object (the curly braces).

这实际上是一个包含单个对象(花括号)的数组(方括号)。

So when you try doing:

所以当你尝试做:

alert(data.name);

This is not correct because the object resides as the first element of the array.

这是不正确的,因为该对象作为数组的第一个元素。

alert(data[0].name);

Should work as you expect.

应该像你期望的那样工作。

#3


Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]

你的JSON作为一个javascript数组返回...用[]包装卷曲位[{}]

so this would work.

所以这会奏效。

wrong:  alert(data.name);
right:  alert(data[0].name);

Hope that helps. D

希望有所帮助。 d

#4


Ok, thanks to Darryl, I found the answer.

好的,多亏了Darryl,我找到了答案。

So here is the functional code for anyone who is wondering about this:

所以这里是任何想知道这个问题的人的功能代码:

javascript file

jQuery(document).ready(function() {

  jQuery('#storeListTable tr').click(function() {

    jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML },     // this.cells[0].innerHTML is the content ofthe first cell in selected table row
      function(data){
         alert(data[0].name);
      }, "json");
    });

});

get_storeData.php

<?php
  include_once('dal.php');

  $storeID = $_POST['storeID'];   //Get storeID from jQuery.post parameter

  $sl = new storeLocator();
  $result = $sl->getStoreData($storeID);  //returns dataset from MySQL (SELECT * from MyTale)

  while ($row = mysql_fetch_array($result))
  {
    $data[] = array( 
    "id"=>($row['id']) ,
    "name"=>($row['name']));
  }  

  $storeData = json_encode($data);

  echo $storeData;
?>

Thanks for all your help guys!

谢谢你们的帮助!