从 javascript 到 PHP 的 Jquery ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6804327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:55:34  来源:igfitidea点击:

Jquery ajax call from javascript to PHP

phpjavascriptajax

提问by user823527

There seems to be a problem with the code I have for calling php from javascript with jquery ajax. The ajax call seems to be successful but I don't get the correct information returned from the php function.

我使用 jquery ajax 从 javascript 调用 php 的代码似乎有问题。ajax 调用似乎成功了,但我没有得到从 php 函数返回的正确信息。

In the php function I create a SQL query. I send back the query as a reponse to debug it before performing a delete query. Here is the HTML for the div to show the query.

在 php 函数中,我创建了一个 SQL 查询。在执行删除查询之前,我将查询作为响应发回以调试它。这是用于显示查询的 div 的 HTML。

 <div id="thenode" style="position: absolute; top: 30px; left: 0px; width: 150px; background-color: white; z-index: 9999;">&nbsp;</div>

Here is the jquery ajax call. There are two variables being sent to the PHP function: nodeid for node to be delete, and option delete for the function.

这是 jquery ajax 调用。有两个变量被发送到 PHP 函数:要删除的节点的 nodeid 和函数的选项删除。

function deleteitem()
{

     //get selected node
     var selectnod = getCookie('pnodid'); 

     //define php info and make ajax call
     $.ajax({
         url: "uptree.php",
         type: "POST",
         data: { node: selectnod, option: "delete" },
         cache: false,
         success: function (response) {
             $('#thenode').html(response);
         }
     });

}

Here is the PHP function.

这是PHP函数。

<?php

function uptree() {

  $node = $_POST['node'];
  $option = $_POST['option'];

  if($node == '' || $option == '') {
    return '';
  }

  $dbco = mysql_connect('localhost', 'root', 'mmowebdb');
  if (!$dbco)
    {
    die('Could not connect: ' . mysql_error());
    }

  mysql_select_db("pagelinks", $dbco);

  $sql = "DELETE FROM dtree_table WHERE nid='$node'";

  return $sql;
}

?>

Should be straightforward but this ajax call returns an empty string and causes the div in the HTML to disappear. This is the first time I use ajax in an actual project. The problem must be easy to find for someone who knows what ajax really does. Can you tell the problems?

应该很简单,但是这个 ajax 调用返回一个空字符串并导致 HTML 中的 div 消失。这是我第一次在实际项目中使用ajax。对于知道 ajax 真正作用的人来说,这个问题一定很容易找到。你能说出问题吗?

回答by user823527

I found the answer! Thanks to all of you who had suggestions about the SQL call. But here is the actual answer to my question.

我找到了答案!感谢所有对 SQL 调用提出建议的人。但这是我问题的实际答案。

There are four steps in making an ajax Javascript to PHP call. The first two steps happen in the Javascript. The other two steps happen in the PHP.

将 ajax Javascript 用于 PHP 调用有四个步骤。前两个步骤发生在 Javascript 中。其他两个步骤发生在 PHP 中。

Step 1. In Javascript decide what variables are needed in the PHP function, retrieve them.

步骤 1. 在 Javascript 中决定 PHP 函数中需要哪些变量,检索它们。

Step 2. Make the ajax call to the PHP function. jquery has a convenient way of passing values to PHP. You have a an array of name-value pairs like this in the data item for the ajax call.

步骤 2. 对 PHP 函数进行 ajax 调用。jquery 有一种向 PHP 传递值的便捷方式。在 ajax 调用的数据项中,您有一个像这样的名称-值对数组。

 data: { node: selectnod, option: "delete" },

Step 3. Have your PHP function ready in a PHP file. Write the function like this.

步骤 3. 在 PHP 文件中准备好 PHP 函数。像这样写函数。

function updatetree($node, $option) {

Step 4. Echo a call to the php function within that PHP file.

步骤 4. 在该 PHP 文件中回显对 php 函数的调用。

With these four steps you should have a succesful call to PHP and be able to return information to javascript from the PHP function.

通过这四个步骤,您应该可以成功调用 PHP,并且能够从 PHP 函数向 javascript 返回信息。

Here is the javascript function.

这是javascript函数。

function deleteitem()
{

     //Get selected node to send to PHP function
     var selectnod = getCookie('pnodid'); 

     //Define php info, specify name of PHP file NOT PHP function
     //Note that by loading the PHP file you will probably execute any code in that file
     //that does not require a function call
     //Send PHP variables in the data item, and make ajax call
     //On success perform any action that you want, such as load a div here called thenode
     $.ajax({
         url: "uptree.php",
         type: "POST",
         data: { node: selectnod, option: "delete" },
         cache: false,
         success: function (response) {
             $('#thenode').html(response);
         }
     });

}

Here is the PHP file uptree.PHP. It has a function defined, called updatetree. It also has an echo statement to call that function. This just seems to be the way to cause the function to run. Ajax itself doesn't call the function.

这是 PHP 文件uptree.PHP。它定义了一个名为updatetree的函数。它还有一个 echo 语句来调用该函数。这似乎是导致函数运行的方法。Ajax 本身不调用该函数。

<?php

//Function defined here
//The variables will come from the ajax data statement
function updatetree($node, $option) {

  if($node == '' || $option == '') {
    return 'Select an item in the tree.';
  }

  $dbco = mysql_connect('localhost', 'root', 'mmowebdb');
  if (!$dbco)
    {
    die('Could not connect: ' . mysql_error());
    }

  mysql_select_db("pagelinks", $dbco);

  $sql = '';
  switch($option) {
     case 'delete':
        $sql = "DELETE FROM dtree_table WHERE nid='$node'";
        break;
     case 'add':
        list($pagename, $address) = explode(",", $page);
        $pagename = trim($pagename);
        $address = trim($address);
        $sql = "INSERT INTO dtree_table (nid, pid, name, url) values (NULL, ".$node.", '".$pagename."', '".$address."')";
        break;
     case 'update':
        break;
  }

  if (!empty($sql)) return $sql;
}

//echo statement to run function, variables sent by ajax are retrieved with $_REQUEST
//they could have also been retrieved with $_GET or $_POST
echo updatetree(trim($_REQUEST['node']),trim($_REQUEST['option']),trim($_REQUEST['page']));

?>

So to recap. Javascript gets variables, makes ajax call to PHP file. Ajax loads PHP file which contains echo statement that causes PHP function to run. That PHP function is defined in that same file. The function return statement sends information back to javascript through ajax. Javascript does something with that information, e.g. load it into a div on the HTML page.

所以要回顾一下。Javascript 获取变量,对 PHP 文件进行 ajax 调用。Ajax 加载包含导致 PHP 函数运行的 echo 语句的 PHP 文件。该 PHP 函数在同一个文件中定义。函数 return 语句通过 ajax 将信息发送回 javascript。Javascript 使用该信息执行某些操作,例如将其加载到 HTML 页面上的 div 中。

回答by Michael Berkowski

You haven't passed $sqlinto mysql_query();

你还没有$sql进入mysql_query();

$sql = "DELETE FROM dtree_table WHERE nid='$node'";

mysql_query($sql);
// -------^^^^^^^^
return $sql;

Your code is vulnerable to SQL injection, as it only checks for an empty $node. As an end user, I could delete any id in the database I wish, or all of them if I ran the code in a loop. You will need something to check that the user running the code has permission to delete the node, and also, call mysql_real_escape_string()on $node.

您的代码容易受到 SQL 注入的影响,因为它只检查空的$node. 作为最终用户,我可以删除数据库中我希望的任何 ID,或者如果我在循环中运行代码,则可以删除所有 ID。你将需要一些东西来检查运行代码的用户有权删除节点,也叫mysql_real_escape_string()$node

$node = mysql_real_escape_string($node);
$sql = "DELETE FROM dtree_table WHERE nid='$node'";
$result = mysql_query($sql);

// Check for success...
if ($result) {
  // return success codes to ajax caller
}
else {
  // return error codes to ajax caller
}

ADDENDUM

附录

We don't see the code where you call upTree()in PHP. Are you actually calling the function? If you don't call it and that's your whole PHP script, then it will execute, do nothing, and return a blank HTTP response to your Ajax calling function with a successful 200 response code.

我们看不到您upTree()在 PHP 中调用的代码。你真的在调用这个函数吗?如果您不调用它并且这就是您的整个 PHP 脚本,那么它将执行,什么都不做,并向您的 Ajax 调用函数返回一个空白的 HTTP 响应,并带有一个成功的 200 响应代码。

回答by Brombomb

You actually need to execute the query you create:

您实际上需要执行您创建的查询:

  $sql = "DELETE FROM dtree_table WHERE nid='$node'";

  $result = mysql_query($sql);

  return $sql;

Then result will contain a Boolean of success status.

然后结果将包含成功状态的布尔值。

Also when you pass it back to the javascript call you may need to set the appropriate page header of plaintext or json (if you decide to use json)

此外,当您将其传递回 javascript 调用时,您可能需要设置适当的纯文本或 json 页面标题(如果您决定使用 json)

I highly recommend using a tool like Firebug to watch each ajax request. Then you can see the posted data, response data, and headers to help you diagnose your issue further. Currently only Firefox (AFAIK) fully supports the firebug extension, but firebug lite is also available for other browsers.

我强烈建议使用 Firebug 之类的工具来观察每个 ajax 请求。然后,您可以查看发布的数据、响应数据和标题,以帮助您进一步诊断问题。目前只有 Firefox (AFAIK) 完全支持 firebug 扩展,但 firebug lite 也可用于其他浏览器。

回答by Magicianeer

I send back the query as a reponse to debug it before performing a delete query.

在执行删除查询之前,我将查询作为响应发回以调试它。

...

...

this ajax call returns an empty string and causes the div in the HTML to disappear.

这个 ajax 调用返回一个空字符串并导致 HTML 中的 div 消失。

I assume you want the query displayed inside your div. You need echo($sql); or echo(uptree()); or equivalent somewhere in your program. You might also create an HTML form that POSTs the same data as your AJAX to see what PHP is returning.

我假设您希望查询显示在您的 div 中。你需要 echo($sql); 或 echo(uptree()); 或程序中某处的等效项。您还可以创建一个 HTML 表单,将与您的 AJAX 相同的数据 POST 以查看 PHP 返回的内容。