我遇到了jquery ajax提交表单的问题。这是jquery代码:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
});
return false;
});
});
</script>
这是表单代码:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5">
<input type="text" id="number" name="number"></input>
<input class="btn btn-small btn-success" type="submit" class="submit" id="submit" name="submit" value="submit">Submit</input>
</form>
updatetextdatabase.php的代码:
<?php
date_default_timezone_set('America/New_York');//set time zone
$con=mysqli_connect('saslaundry.db.10410357.hostedresource.com', 'saslaundry', 'password', 'saslaundry');//establish connection
// Check connection
if (mysqli_connect_errno())//ping database to check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();//error message
}
mysqli_query($con,"INSERT INTO textrequests VALUES('$_GET[number]', '$_GET[machine_id]') ");
return;
?>
但不仅是它没有提交表单,页面也会重新加载,这是我试图通过使用AJAX避免的。我觉得问题是该功能没有被提交按钮调用,但我无法弄清楚原因。
谢谢!
答案 0 :(得分:1)
尝试使用此e.preventDefault();
,阻止您的表单提交,然后执行ajax
来电
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
e.preventDefault();
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
success: function (data) {
//do something here when you got the response
}
});
});
});
</script>
答案 1 :(得分:1)
我让这个工作小提琴:
HTML:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5" />
<input type="text" id="number" name="number" />
<input class="btn btn-small btn-success" type="button" class="submit" id="submit" name="submit" value="submit" />
</form>
Jquery的:
$(document).ready(function(){
$("#submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString
});
});
});
网络控制台:
Request URL:http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php
Request Headersview source
Accept:*/*
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://fiddle.jshell.net
Referer:http://fiddle.jshell.net/WJGhr/show/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Form Dataview sourceview URL encoded
number:25
machine_id:5