php - 如何通过 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);
});
}
希望我已经清楚了,谢谢。对不起,如果问题可能是新手。
解决方案
我想您是在问如何从表单字段中获取数据并将其放入 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/
推荐阅读
- java - 如何在 jooq 中使用 mysql SEC_TO_TIME 函数
- laravel - Laravel + Vue ssr。预取数据
- dart - 颤动中的错误:文档引用必须有偶数个段
- android - 深度链接过程的通用 URL | 安卓 | IOS | 网络
- android - 我在 Firebase In App 消息中收到错误消息?
- json - 将 json 数据获取到 swift uitable 视图中
- sql - Graphql、node.js 和 sql,不能为不可为空的字段返回 null
- reactjs - 如何在反应引导表2标题单元格中向单元格添加复选框?
- android - 从联系人选择器意图中获取人员的联系方式
- python - Identify groups of numbers in an array (group pixels of an image)