以下代码,
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
/*<![CDATA[*/
$(document).ready(function () {
var value = $('#button input').val();
var name = $('#button input').attr('name');
$('#button input').remove();
$('#button').html('<a href="#" class="cssSubmitButton" rel=' + name + '>' + value + '</a>');
//global vars
var form = $("#customForm");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
//On blur
name.blur(validateName);
email.blur(validateEmail);
//On key press
name.keyup(validateName);
email.keyup(validateEmail);
//On Submitting
$('#button a').on('click', function () {
var link = $(this);
if(validateName() & validateEmail())
{
var link = $(this);
var str = $("form").serialize();
jQuery.ajax({
url : 'load.php',
data: str,
type: 'GET',
cache: 'false',
dataType: "json",
beforeSend: function () {
link.addClass('loading');
},
success: function(data) {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
},
error:function(x,e){
if(x.status==0)
{
alert('You are offline!!\n Please Check Your Network.');
}
else if(x.status==404)
{
alert('Requested URL not found.');
}
else if(x.status==500)
{
alert('Internel Server Error.');
}
else if(e=='parsererror')
{
alert('Error.\nParsing JSON Request failed.');
}
else if(e=='timeout')
{
alert('Request Time out.');
}
else
{
alert('Unknow Error.\n'+x.responseText);
}
}
});
return true
}
else
{
return false;
}
});
//validation functions
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
//if it's valid email
if(filter.test(a)){
email.removeClass("error");
emailInfo.text("Valid E-mail please, you will need it to log in!");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else{
email.addClass("error");
emailInfo.text("Stop cowboy! Type a valid e-mail please :P");
emailInfo.addClass("error");
return false;
}
}
function validateName(){
//if it's NOT valid
if(name.val().length < 4){
name.addClass("error");
nameInfo.text("We want names with more than 3 letters!");
nameInfo.addClass("error");
return false;
}
//if it's valid
else{
name.removeClass("error");
nameInfo.text("What's your name?");
nameInfo.removeClass("error");
return true;
}
}
});
/*]]>*/
</script>
我的HTML论坛:
<form method="post" action="" id="subscribeForm" name="subscribeForm">
<fieldset>
<label>Name: </label><input type="text" class="effect" name="name" id="name" autocomplete="off" >
<span id="nameInfo">What's your name?</span>
</fieldset>
<fieldset>
<label>Email: </label><input type="text" class="effect" name="email" id="email" autocomplete="off" >
<span id="emailInfo">Valid E-mail please, you will need it to log in!</span>
</fieldset>
<div id="button">
<input type="submit" value="Subscribe" name="subscribeForm"/>
</div>
<div id="success">
<strong>Data Saved Successfully.</strong>
</div>
</form>
它给我错误:解析JSON请求失败。
这是我在萤火虫中得到的,
load.php?name=asdf&email=ASDF%40gmail.com
这是我的PHP代码
<?php
sleep(3);
echo parse_str($_POST['str']);
?>
答案 0 :(得分:1)
只需使用.serializeArray()
方法:
var str = $("form").serializeArray();
答案 1 :(得分:0)
试试这个:
jQuery.ajax({
url : 'load.php',
data: str,
type: 'POST',
cache: 'false',
dataType: "json",
beforeSend: function () {
link.addClass('loading');
},
success: function(data) {
link.removeClass('loading');
$('#button').css('display','none');
$('#success').css('display','block');
var json = JSON.parse(data);
alert(json.response); // Here you get the value
},
error:function(x,e){
if(x.status==0)
{
alert('You are offline!!\n Please Check Your Network.');
}
else if(x.status==404)
{
alert('Requested URL not found.');
}
else if(x.status==500)
{
alert('Internel Server Error.');
}
else if(e=='parsererror')
{
alert('Error.\nParsing JSON Request failed.');
}
else if(e=='timeout')
{
alert('Request Time out.');
}
else
{
alert('Unknow Error.\n'+x.responseText);
}
}
根据jQuery Documentation, dataType 是您希望从服务器返回的数据类型,而不是发送给它的数据。使用POST并直接发送表单序列化就足够了,因为序列化是HTTP请求数据的实际格式。它将直接转换为$ _POST值。
在服务器端:
<?php
sleep(3);
$str = $_POST['str'];
// Do whatever processing you need here with $str...
// Set an array containing the response (it will be translated to JSON later)
// You can use any kind of array, then you'll access the values like this in Javascript:
// var resp = JSON.parse(data);
// alert( resp.response );
// or: alert( resp.whateverKeyYouUsed );
$ret = array( "response" => "Some response message." );
// Because the script is expecting a JSON response, encode the array and print it
// The response would be something like {"response":"Some response message."} which is JSON
echo json_encode($ret);
?>
答案 2 :(得分:0)
<强>建议:强>
data: str
”更改为data: {str:str}
parse_str($_POST['str']);
更改为parse_str($_GET['str']);
因为,您在 ajax 中使用了“ GET ”方法。parse_str
converts all the query string in php var
。之后,
parse_str($_GET['str'])
您可以按echo $name;
然后,您可以通过 data.name
从 AJAX 响应中获取名称<?php
parse_str($_GET['str']);
echo json_encode(array(
'name' => $name
));
?>
//or
<?php
parse_str($_GET['str'], $response);
echo json_encode($response);
?>