我已经对这个主题进行了详尽的研究,但是由于讨论的分散性以及每个人似乎都有非常不同的用例,因此似乎找不到答案。
我正在使用JQuery mobile通过$ .ajax()调用将数据发送到PHP登录/注册脚本。看来,我尝试发送的数据永远不会发送到要评估的服务器,而我对此感到茫然。
我正在尝试从此表单发送数据:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
这是由以下javascript触发的:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
发送到此php脚本的代码:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
但是,如前所述,if / else块检测到甚至没有设置$ _POST ['formDataReg']。当我尝试使用它为变量赋值时,它显然没有要赋值的数据,并且我得到了空值。
我使用警报来验证formDataReg确实在将其传递给ajax调用中的服务器之前保存了正确的表单值。它以某种方式在ajax调用中丢失,或者我无法正确访问它。
如果有人能指出我正确的方向,我将不胜感激。
这样:
var formDataReg = $("#reg_form").serialize();
您将表格序列化为表格。现在中formDataReg
有这样的内容:
[email protected]®_pass=yyy®_pass_conf=yyy
您必须在您的php文件中解析此查询:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
但是您尝试使用$_POST['formDataReg']
未发送的内容。所以这是错误的。是的,您formDataReg
的JS中有变量,但这没有任何意义。您已经使用ajax请求发送了序列化的字符串(查询),并且不得不处理它。
所以这段代码:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
将无法工作,因为您尚未发送,formDataReg
并且此键在$_POST
数组中没有任何值。
这:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
应该可以正常工作。
让我知道有什么不清楚的地方。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句