过去两天我一直在研究这个应用程序,我似乎无法解决这个问题。我使用Sam Croft's Example来创建表单并将数据发布到mysql中。它可以在浏览器中完美地运行,但不适用于移动设备。
这是我的表格
<form id="registerForm">
<div id="register-thankyou" style="display: none;">
Thank you.
</div>
<div id="register-form">
<p class="mandatory" style="color:#A00;font-weight:700;">* indicates Required</p>
<div data-role="fieldcontain" class="text-field">
<label for="fullname">Full Name*:</label>
<input type="text" name="fullname" value="" placeholder="" class="required" id="fullname" />
</div>
<div data-role="fieldcontain" class="text-field">
<label for="email">Email Address*:</label>
<input type="email" name="email" value="" placeholder="" class="required" id="email" />
</div>
<div data-role="fieldcontain">
<input type="submit" value="Register !!!" />
</div>
</div>
</form>
我的JavaScript register.js
$('#registerForm').submit(function() {
var url = 'http://my-domain.com/register.php';
var postData = $(this).serialize();
var $fname = $('#fullname').val();
var $email = $('#email').val();
if ($fname == "" && $email == "") {
alert('Please fill in all the fields.');
} else {
//submit the form
$.ajax({
type: "POST",
url: url,
crossDomain: true,
cache: false,
async:true,
data: postData,
success: function (data) {
console.log(data);
alert(data);
$('#register-thankyou').show();
$('#register-form').hide();
},
error: function(){
console.log(data);
alert('There was an error while registering. Please, Try again later!');
}
}); //$.ajax
}
return false;
});
我的register.php
include 'config.php';
header('Access-Control-Allow-Origin: *');
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);
$full_name = mysql_real_escape_string($_POST["fullname"]);
$email = mysql_real_escape_string($_POST["email"]);
$sql = "INSERT INTO register (fullName,email) ";
$sql .= "VALUES ('$full_name', '$email')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Registered record added";
}
mysql_close($con);
我尝试过的所有内容:
localhost
添加了对所有来源header('Access-Control-Allow-Origin: *')
在Ajax调用中设置crossDomain: true
实现上述所有功能后,我似乎无法通过Android移动设备将数据发布到mysql中。通过浏览器正常工作。
答案 0 :(得分:0)
尝试使用序列化方法将您的javascript更改为此
$('#submitButton').click(function() {
var url = 'http://my-domain.com/register.php';
formData = {
fullname: $('#fullname').val(),
email: $('#email').val()
}
if ($('#fullname').val() == "" && $('#email').val() == "") {
alert('Please fill in all the fields.');
} else {
//submit the form
$.ajax({
type: "POST",
url: url,
crossDomain: true,
cache: false,
async: true,
data: formData,
contentType: 'application/json',
success: function(data) {
console.log(data);
alert(data);
$('#register-thankyou').show();
$('#register-form').hide();
},
error: function() {
console.log(data);
alert('There was an error while registering. Please, Try again later!');
}
}); //$.ajax
}
});
然后添加submitButton id
HTML
<input id="submitButton" type="submit" value="Register !!!" />