[英]Basic AJAX async false passing values to, from javascript html
也許這是一個非常基本的問題,而且我是絕對的初學者,我認為我對AJAX的工作方式有很多缺陷。 有人可以幫忙解釋一下如何使此代碼有效嗎?
我有一個同步的AJAX調用,想在兩者之間傳遞值。 我了解同步功能的概念,但是在這種情況下需要將此設置為false,因為需要先驗證用戶名,然后腳本才能繼續。
關於調用方發生的事情有很多示例,但是對於調用方發生的事情卻一無所獲。
我的代碼遵循以下原則:
來電顯示:
$.ajax({
url: 'http://<domain>/checkpassword.html',
data: {
username: $('#username').val(),
password: $('#password').val()
},
type: 'POST',
asynch: 'false',
dataType: 'json',
success: function(data) {
alert('User is valid');
alert('The returned value is' + (?returned value?));
},
error: function() {
alert('User is not accepted');
}
});
調用代碼:
<html>
<script>
if (username = 'ABC123') {
return 'Accepted'
} else {
return 'Rejected'
}
</script>
</html>
問題:
如何在調用的代碼中獲取用戶名的值?
如何在調用代碼中訪問“ Accepted”或“ Rejected”的文字返回值?
UPDATE
遵循ppajer的建議。
我已經更改了代碼以調用php文件。
調用代碼現在看起來像:
<!--Put the following in the <head>-->
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=11">
<html>
<script>
(window.jQuery || document.write('<script src="http://<domain>/jquery-3.1.1.js"><\x3C/script>'));
(function defer() {
if (window.jQuery) {
jQueryLoaded();
} else {
setTimeout(function() { defer() }, 50);
}
})();
function jQueryLoaded() {
$("document").ready(function(){
$.ajax({
url: 'ajaxcalled.php', //This is the current doc
type: "POST",
data: {username: "ABC123", season: "Winter", email: "winter@northpole.com"},
success: function(data){
console.log(data);
}
});
})
}
</script>
</html>
調用的php文件現在看起來像
<!DOCTYPE html>
<html>
<body>
<?php
$username = $_POST['username'];
$season= $_POST['season'];
$email= $_POST['email'];
echo "<script> alert('My username is '" + $username + "')</script>";
?>
</body>
</html>
呼叫者代碼成功返回,但是未顯示任何警報。
如何在調用php文件時運行腳本?
HTML不適合后端邏輯。
除了$.ajax
選項中的“ asynch”處於async
之外,問題在於您正在請求HTML頁面,但請求的dataType
期望響應為JSON。
您的用例將要求您使用服務器端語言(如PHP)來處理請求。 然后,您可以返回一個正確的JSON響應,您的AJAX腳本會很樂意接受並從那里繼續。
編輯
確保處理請求的后端代碼除了要輸出的實際值外,不輸出任何東西。 不需要使用任何<html></html>
或<script>
標記,因為服務器返回的字符串將傳遞到$.ajax
的回調中。 另外,擴展名應為.php而不是.html。 考慮服務器端邏輯時,只需完全忘記HTML。
例如,如果您的服務器端代碼在checkpassword.php
看起來像這樣
<?php
$username = $_POST['username'];
echo $username;
?>
您可以像這樣在回調中訪問$username
的值
$.ajax({
url: 'http://<domain>/checkpassword.php', //note the extension
data: {
username: $('#username').val(),
password: $('#password').val()
},
type: 'POST',
async: 'false',
dataType: 'json',
complete: function (response) {
alert('Username is '+response);
}
});
在完整的回調中,作為參數傳遞的response
變量包含服務器返回的全部內容。
試用不同的選項,選擇使用getscript選項。
在調用程序中設置全局值,可以在被調用程序中訪問
username = 'myname';
$.getScript("http://<domain>/ajaxcalled.js", function(){
alert("Script loaded and executed.");
})
所謂的js簡單地有
alert('hi');
alert(username);
用戶名成功顯示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.