[英]Getting data to php when <form> '.submit' function overridden (using ajax)?
我已覆盖此网页上表单的.submit函数,因为该网页已加载在“ index.php”中的#mainContent内,并且我希望“提交”按钮仅替换此#mainContent。
我正在尝试将数据从此表单获取到.php文件,以便对数据库进行查询(或简单地回显已填充的变量,以指示已传递数据)。
我是AJAX的新手。 有人可以向我解释如何将数据传递到.php文件,或者指向要提供一些澄清信息的资源吗?
现在,我只是试图将字符串传递给变量,然后将其回显。
有人可以澄清“数据:{thisElement:notThisOne}”中的第一个元素是什么吗? 它是表单中属性的“名称”吗? 变量的名称将传递给'url:'中的php脚本?
感谢您澄清这一点。
这是我的“ search.html”文件(嵌入在另一个“ index.php”文件中):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="main" data-role="content" id="main">
<div id="holder">
<h1>Search</h1>
<div class="left">
<form name="searchForm" id="searchForm" onsubmit="return false;">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<legend><h3>Course</h3></legend>
<select name="courseSelect" id="courseSelect" name="courseSelect">
<option value="*">All</option>
<option value="COMM2216">COMM-2216</option>
</select>
</fieldset>
<p>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<legend><h4>Type:</h4></legend>
<input type="radio" name="lecLab" value="lec" id="lec"/>
<label for="lec">Lecture</label>
<input type="radio" name="lecLab" value="lab" id="lab">
<label for="lab">Lab</label>
<input type="radio" name="lecLab" value="*" id="both" checked="checked">
<label for="both">Both</label>
<p>
</fieldset>
<input type="submit" value="Go">
</form>
</div>
</div>
</div>
<script src="./scripts/searchGo.js"></script>
</body>
</html>
“ searchGo.js”:
$(document).ready(function() {
$("#searchForm").submit(function(e)
{
//e.preventDefault();
$.ajax({
type: "POST",
url: "./scripts/php_test.php",
data: {courseSelect: "Lecture, or Lab?"},
success: function(){
alert($lecOrLab);
$("#holder").load("./scripts/php_test.php");
}
}) ;
});
});
最后,'php_test.php':
<html>
<head>
</head>
<body>
<?php
$courseSelect = $_POST['courseSelect'];
echo ($courseSelect);
?>
</body>
</html>
我是否在php_test.php中错误地收集了数据? 还是在“ data:{}”(searchGo.js的)中错误地分配了它?
感谢您的澄清。
首先,您不应该使用POST执行搜索,也没有修改状态(删除或更新记录)。 请改用GET请求。
ajax请求中的数据就是您想要传递给请求的数据。 使用jQuery序列化将一组表单元素编码为提交字符串。
$.ajax({
type: "GET",
url: "./scripts/php_test.php",
data: $("#searchForm").serialize(),
success: function(data){
$("#holder").html(data);
}
});
现在,在您的php文件中,您应该查看$ _GET。 像这样:
$courseSelect = $_GET['courseSelect'];
//now query your db and return your results based on your form fields.
PHP尝试:
echo json_encode($courseSelect);
Javascript:我看不到$ lecOrLab定义在哪里? 同样对于成功方法,您没有正确获得响应。 尝试这个:
success: function(response){
var resp = $.parseJSON(response);
console.log(resp);
// do stuff with resp
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.