AJAX POST-如何在PHP中使用js变量 [英] AJAX POST - how to use a js variable in PHP

查看:198
本文介绍了AJAX POST-如何在PHP中使用js变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次加载页面时,POST数据数组中将没有任何内容.运行后,我希望能够使用PHP代码中的POST数据中发送的任何变量,以便可以根据发送的参数查询数据库.我需要以某种方式重新加载页面吗?

The first time the page loads, there will not be anything in the POST data array. After it runs I want to be able to use whatever variable I send in the POST data in the PHP code so I can query my database based on parameters sent. Do I need to reload the page somehow to do this?

if(isset($_POST['boarder'])){
    $boarder = $_POST['boarder'];
    function boarderCheck($boarder){
        echo "<script type ='text/javascript'>alert('$boarder');</script>";
    }
    boarderCheck($boarder);
} else {
?>
  <script defer src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="map.js"></script>
<?
};
?>

JavaScript(map.js)

$.ajax({
  type: "POST",
  data: {boarder: 'test'},
  dataType: 'text',
  success: function(response) {
    console.log(response);
  }
})

推荐答案

否,您不需要重新加载页面,尤其是因为您使用的是异步请求(中的 A AJAX )添加到相同的网址.

No you don't need to reload the page, especially since you are utilizing an asynchronous request (the A in AJAX) to the same URL.

请参见此phpfiddle 演示您的示例(进行了一些修改).单击运行-F9 按钮,然后单击标有 Board 的按钮以运行JavaScript(带有AJAX请求).如果打开浏览器控制台,则应该在网络标签中看到请求.主要的应该是对 code_41096139.php 之类的页面的GET请求(数字可能会发生变化).然后,当发出AJAX请求时,应该对同一页面有一个POST请求.展开该请求,您应该会看到表单数据.

See this phpfiddle demonstrating your example (with a couple modifications). Click the Run - F9 button and then click the button labeled Board to run the JavaScript (with the AJAX request). If you open the browser console, you should see the requests in the Network tab. The main one should be a GET request to a page like code_41096139.php (the numbers will likely change). Then when the AJAX request is made, there should be a POST request to that same page. Expand that request and you should see the Form data.

除了添加按钮和单击处理程序外,所做的唯一修改是添加输出元素:

The only modifications made, besides adding the button and click handler, were to add the output element:

<div id="output"></div>

,然后在AJAX请求的成功回调中,将该元素的文本设置为响应(除了对console.log()的调用):

and then in the success callback of the AJAX request, set the text of that element to the response (in addition to the call to console.log()):

 success: function(response) {
      $('#output').text('response: '+response);
      console.log(response);
 }

这篇关于AJAX POST-如何在PHP中使用js变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆