我想使用该按钮在Ajax请求english.json和french.json之间切换,但是我不确定如何操作。有谁可以帮助我吗?下面的代码仅调用JSON中的每个对象。
<!doctype html>
<html>
<body>
<h1> Frenching</h1>
<button id="toggle"> toggle</button>
<p> This program changes names from English to French</p>
<h3 id="name"> </h3>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"> </script>
<script>
//Ajax request
$("document").ready(function () {
$.getJSON("French.json").done(function (french) {
console.log(french.lastName)
});
$.getJSON("english.json").done(function (english) {
console.log(english.lastName)
});
});
</script>
//seperate files
French.Json
{
"firstName": "Merci",
"lastName": " Claudè"
}
English.Json
{
"firstName": "Gracias",
"lastName": "Claude"
}
答案 0 :(得分:1)
我创建了一个全局对象以将对象存储在JSON中,然后创建了一个触发英语和法语json的切换功能。
//sets a global variable
var globalState = {
viewState: true,
english: null,
french: null
};
//toggles function
$("#toggle").click(function toggleGlobalState () {
globalState.viewState = !globalState.viewState; // sets the viewState object to false
console.log(globalState); // toggles true and false
if(globalState.viewState) { // if true change name to french
$("#firstname")[0].innerHTML = globalState.french.firstName
$("#lastname")[0].innerHTML = globalState.french.lastName
} else { // if false change name to english
$("#firstname")[0].innerHTML = globalState.english.firstName
$("#lastname")[0].innerHTML = globalState.english.lastName
}
});
//Ajax request
$("document").ready(function () {
$.getJSON("French.json").done(function (french) {
globalState.french = french; // sets the french name objects in the json to a global object
$("#firstname")[0].innerHTML = globalState.french.firstName
$("#lastname")[0].innerHTML = globalState.french.lastName
}).then(function(result) {
console.log(globalState.french.firstName); //checks
});
$.getJSON("english.json").done(function (english) {
globalState.english = english; // sets the english name objects in the json to a global object
});
});
答案 1 :(得分:0)
如果您不介意同时调用这两个Ajax请求,则应将结果存储在变量中,然后切换结果。
1,14
如果只想在需要时触发该ajax,则应在按下按钮时触发它。
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random myRandom = new Random();
int suitNo, cardNo;
string suit = "", card = "";
suitNo = myRandom.Next(1, 5);
cardNo = myRandom.Next(1, 14);
if (suitNo == 1)
{
suit = "Hearts";
}
if (suitNo == 2)
{
suit = "Diamonds";
}
if (suitNo == 3)
{
suit = "Clubs";
}
if (suitNo == 4)
{
suit = "Spades";
}
switch (cardNo)
{
case 1:
card = "Ace";
break;
case 2:
card = "Two";
break;
case 3:
card = "Three";
break;
case 4:
card = "Four";
break;
case 5:
card = "Five";
break;
case 6:
card = "Six";
break;
case 7:
card = "Seven";
break;
case 8:
card = "Eight";
break;
case 9:
card = "Nine";
break;
case 10:
card = "Ten";
break;
case 11:
card = "Jack";
break;
case 12:
card = "Queen";
break;
case 13:
card = "King";
break;
}
label1.Text = "Your card is a " + card + " of " + suit;