[英]How would I go about retrieving a JSON encoded PHP echo to an AJAX script?
我正在尋找將注冊表單的PHP回聲檢索到AJAX腳本中,以防止頁面刷新。 我瀏覽了一些教程,但似乎都沒有滿足我的需求。
作為一個AJAX / JSON新手,我希望我能在正確的方向上獲得一些指導。
注冊表由多種變量組成,例如($ first_name),($ last_name),但這是我要檢索的示例,因為所有回聲都采用類似的格式:
if (strlen($_POST['username']) < 2){
{
echo "Invalid username, must be at least 3 characters.";
exit;
}};
if (strlen($_POST['username']) > 25){
echo "Invalid username, must be no more than 24 characters.";
exit;
}
if (strlen($_POST['password']) < 5){
echo "Invalid password, must be at least 5 characters.";
exit;
}
if (strlen($_POST['password']) > 32){
echo "Invalid password, must be a maximum of 32 characters.";
exit;
}
我最初嘗試過:
我最初有這樣的東西,但是我不確定如何應用它:
json_encode(array("error"=>1, "message"=>"I suck at AJAX."));
但是在努力創建對應的AJAX腳本后便將其報廢。
我重構了您的代碼:
$status ="";
if (strlen($_POST['username']) <= 3){
$status = "Invalid username, must be at least 3 characters.";
} else if (strlen($_POST['username']) > 24){
$status = "Invalid username, must be no more than 24 characters.";
} else if (strlen($_POST['password']) <= 5){
$status = "Invalid password, must be at least 5 characters.";
} else if (strlen($_POST['password']) > 32){
$status = "Invalid password, must be a maximum of 32 characters.";
} else {
$status = "ok";
}
echo json_encode(array('status' => $status));
jQuery腳本:
<script>
$.ajax({
url: 'ajax.php',
type: 'POST',
data: { 'username: "hello", password : "hello2"} ,
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
</script>
您可以創建一個可以為您處理的函數:以下示例:
function json_alert($alert_type,$alert_msg) {
ob_end_clean(); //this will removing any previous output, very important because json will be invalid with other output
echo json_encode (array(
"alert_type" => $alert_type,
"alert_msg" => $alert_msg
));
exit(); //required too,this ends execution
}
現在我們有了函數,您可以像這樣調用它:
if (strlen($_POST['username']) < 2) {
json_alert("error","Invalid username, must be at least 3 characters.");
}
if (strlen($_POST['username']) > 25) {
json_alert("error","Invalid username, must be no more than 24 characters.");
}
if (strlen($_POST['password']) < 5) {
json_alert("error","Invalid password, must be at least 5 characters.");
}
if (strlen($_POST['password']) > 32) {
json_alert("error","Invalid password, must be a maximum of 32 characters.");
}
現在在Jquery中,這就是您將如何做的
$.ajax({
dataType : "json",// we need json back
data : $("form").serialize(),//get form data
url: "http://url-of-login-processor",
type : "POST" // Either POST or GET method
}).done(function(callback) {
if(callback.alert_type =="error") {
//what to do if error
}else{
//what to do if success
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.