javascript - 如何从 JQuery Ajax 请求中获取 "data"

标签 javascript php jquery ajax

<分区>

这是我在 index.html 上的代码:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script>
            $.ajax({
                type: "POST",
                url: 'test.php',
                data: "check",
                success: function(data){
                    alert(data);
                }
            });
        </script>
    </head>
    <body>
        <div></div>
    </body>
</html>

如何对 test.php 进行编程以获取在 AJAX API 中发送的“数据”?

最佳答案

您在这里问的是一个非常基本的问题。您应该首先阅读一些 Ajax 教程。只是为了帮助您一点点(假设您知道发送数据的 GET 和 POST 方法),数据中的“数据”:“检查”与函数(数据)中的“数据”不同。为清楚起见,您应该将它们命名为不同的名称:

$.ajax({
     type: "POST",
     url: 'test.php',
     data: "check",
     success: function(response){
         alert(response);
     }
});

这清楚地表明,一个是您在 POST 参数中发送到 test.php 文件的数据,另一个是您在运行后从 test.php 文件获得的响应。事实上,您 POST 到 test.php 的数据参数必须是像这里一样的散列(我在这里假设键为“类型”:

$.ajax({
     type: "POST",
     url: 'test.php',
     data: {"type":"check"},
     success: function(response){
         alert(response);
     }
});

数据中显然可以有更多的键值对。

因此,假设您的 test.php 文件是这样的:

if(isset($_POST['type'])){
  //Do something
  echo "The type you posted is ".$_POST['type'];
}

在这种情况下,您的提醒应显示为:“您发布的类型是支票”。这将根据您在 AJAX 调用中为“type”键发送的值而改变。

关于javascript - 如何从 JQuery Ajax 请求中获取 "data",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27700513/

相关文章:

Javascript:如何动态创建和合并文本节点?

javascript - 使用 Json 和 BS4 抓取 HTML 中的脚本标签

javascript - 为什么我不能删除 Mongoose 模型的对象属性?

php - 无法安装 php 5.6 mssql - Centos 7

javascript - 为什么显示两个垂直滚动条?

javascript - 如何将 slider 范围方向更改为 RTL?

php - 比较php中的两个整数

php - 在单个 SELECT 查询中设置 enable_seqscan = off

php - 使用 Ajax 动态加载内容

css - 更改 JQuery 中 .toggle() 动画的 'origin'