这段代码获取所有表单变量,并通过AJAX将它们发送到PHP脚本。但我希望通过JSON编码数组返回到javascript的PHP脚本的计算结果为“post”形式:{“uname”:“someNamefromForm”,“email”:“someEmail”,“ FNAME “:” namefromtheform”, “L-NAME”: “lastnamefromform” 我现在得到的输出是“uname = e& email = e& fname = e& lname = euname”..这是我想在页面底部显示的JSON数组,用于调试目的。有人可以告诉我如何格式化它
这是我的HTML表单
<div id="wrapper">
<h2> Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="uname" value="" />
</div>
<div>
<label for="email">Email Address <em>*</em></label>
<input id="email" type="text" name="email" value="" />
</div>
<div>
<label for="fname" class="error">First Name <em>*</em></label>
<input id="fname" type="text" name="fname" value="" size="50" class="error"/>
<p class='note'>All error message go here </p>
</div>
<div>
<label for="lname">Last Name <em>*</em></label>
<input id="lname" type="text" name="lname" value="" size="50" />
</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
<a >Refresh this Page</a>
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
这是我的javascript
$("#ajax-form").submit(function(){
var variableToSend = $(this).serialize();
$.post(
'ajaxformval_post.php',
{variable: variableToSend},
function(data){$("#debug").html(data)},
"json"
);
})
这是php
<?php
$variable = $_POST['variable'];
echo json_encode($variable);
/*$json = array(
'booleanFlag' => TRUE,
'someText' => "AJAX should be renamed AJAJ",
'anArrayOfData' => array('name' => 'Mickey', 'ears' => 'very Big')
);*/
?>
答案 0 :(得分:1)
您可以直接发送序列化变量:
$("#ajax-form").submit(function(){
var variableToSend = $(this).serialize();
$.post(
'ajaxformval_post.php',
variableToSend,
function(data){$("#debug").html(data)},
"json"
);
});
然后在服务器端输出json_encoded帖子:
<?php
$variable = $_POST;
echo json_encode($variable);
?>
答案 1 :(得分:0)
您是否尝试从$ .post-method更改&#34; json&#34; -parameter?
根据文件https://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
所以我想如果你给他&#34; json&#34;他会自动解码返回的数据。