如何通过ajax或任何http请求获取$_get url中的参数



例如,我将此表单发送到queries.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,也可以是参数较少且可变的url。

如果我有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);
});

}

希望我已经说清楚了,谢谢。很抱歉,如果这个问题可能是新手。

我想您在问如何从表单字段中获取数据并将其放入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/

使用JQuery AJAX的数据属性。

$.ajax({
type: "GET",
url: "queries/queries.php?",
data: {name1: variable1, name2: variable2, name3: variable3},
dataType: "json",
contentType: "application/json",
}).done(function (data) {
console.log(data);
}).fail(function (response) {
console.log(response);
});

其中variable1、variable2、variable3是变量,name1、name2、name3是GET变量。因此,在PHP中,您将收到它们$name1=$_GET["name1"];

如果你有html表单,并且想使用AJAX提交整个表单,请使用@ADyson的方法,因为它可以提交整个表单并且更容易编写和更干净。