首页 > 解决方案 > 如何通过 ajax 或任何 http 请求获取 $_GET url 中的参数?

问题描述

例如,我有这个表单,我发送到 query.php。

echo "<form method='GET' action='queries.php'>
       <label>name1</label>
       <input type='checkbox' name='name1'/>
       <label>name2</label>
       <input type='checkbox' name='name2'/>
       <label>name3</label>
       <input type='checkbox' name='name3'/>
       <input type='submit' name='sendData' value='Send'/>
      </form>";

为了执行 ajax 调用,url 可以是queries.php?name1=on&name2=on&name3=on&SendData=Send或带有更少和可变参数。

如果我有 main.js,如果我发送的参数是变量,我如何访问 url?对于变量,我的意思是它们并不总是相同的。

$.ajax({
type: "GET",
url: "queries/queries.php?",
dataType: "json",
contentType: "application/json",
}).done(function (data) {
  console.log(data);

}).fail(function (response) {
  console.log(response);

});

}

希望我已经清楚了,谢谢。对不起,如果问题可能是新手。

标签: phpajax

解决方案


我想您是在问如何从表单字段中获取数据并将其放入 URL 中?

如果是这样,最简单的方法是处理表单的提交事件,然后让 jQuery 为您序列化表单的数据,并在您的 AJAX 请求中将其发送到服务器。

例如:

HTML(注意表格上的 ID):

<form method='GET' id="someForm" action='queries.php'>
   <label>name1</label>
   <input type='checkbox' name='name1'/>
   <label>name2</label>
   <input type='checkbox' name='name2'/>
   <label>name3</label>
   <input type='checkbox' name='name3'/>
   <input type='submit' name='sendData' value='Send'/>
</form>

JavaScript/jQuery:

$(function() { //wait till page has loaded
  $("#someForm").submit(function(event) { //add "submit" event handler to the form
    event.preventDefault(); //stop normal postback behaviour
    $.ajax({
      type: "GET",
      url: "queries/queries.php?",
      data: $(this).serialize() //grab the form data
      dataType: "json",
    }).done(function (data) {
      console.log(data);
    }).fail(function (response) {
      console.log(response);
    });
  });
});

serialize()将自动输出一个查询字符串(就像您在问题中显示的那样),对于 GET 请求,将其附加到 URL - 尽管对于这样的表单,通常最好使用 POST 提交,但这取决于您。文档:https ://api.jquery.com/serialize/


推荐阅读