我正在尝试将可重用的AJAX库用于同一文件中的其他功能。可重用的AJAX基础的主要目的是最小化AJAX代码,从而在其他函数中重用基础。
在没有调用变量的行中它工作正常。 (参见标有&#34的行;这些行有效"。当试图从另一个函数调用AJAX基函数时,因此包括一个传递给AJAX库的变量,它不起作用。
问题:特定于AJAX,如何从AJAX函数中调用外部变量的正确方法?
Index.json -file内容:
{
"firstName": "John",
"lastName": "Doe"
}
Index.js -file content:
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
document.getElementById("boxOne").innerHTML = response.[fname];
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase(fname = "firstName"); // Passing in variable into function.
}
function changeLastName() {
ajaxBase(lname = "lastName"); // Passing in variable into function.
}
Index.html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title>
</head>
<body>
<button type="button" name="button" onclick="changeFirstName()">Change first-Name</button>
<button type="button" name="button" onclick="changeLasttName()">Change last-Name</button>
<div id="boxOne" class="boxOne">First-Name[placeholder]</div>
<div id="boxTwo" class="boxTwo">Last-Name[placeholder]</div>
<script src="index.js"></script>
</body>
</html>
答案 0 :(得分:-1)
您可以尝试在ajaxBase
上定义两个参数,并在函数体内检查它们。当您调用它时,将其中一个指定为null以指示哪个值不需要更改。
/************************************/
/* Ajax base to fetch external json */
/************************************/
function ajaxBase(fname, lname) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = JSON.parse(xhttp.responseText);
//document.getElementById("boxOne").innerHTML = response.firstName; // This line works.
//document.getElementById("boxTwo").innerHTML = response.lastName; // This line works.
if (fname !== null)
document.getElementById("boxOne").innerHTML = response.[fname];
if (lname !== null)
document.getElementById("boxTwo").innerHTML = response.[flname];
}
};
xhttp.open("GET", "index.json", true); // Define source json data file.
xhttp.send();
}
function changeFirstName() {
ajaxBase("firstName", null);
}
function changeLastName() {
ajaxBase(null, "lastName");
}