[英]How to display data storing in ajax global variable?
The user selects one of the options and submits the form. 用户选择选项之一并提交表单。
Then without submitting the form, I need to display data from json file. 然后,无需提交表单,我需要显示json文件中的数据。
I am storing ajax call in a global variable display_this
and calling that variable as a function after form is submitted. 我将ajax调用存储在全局变量display_this
并在提交表单后将该变量作为函数调用。
When I select option and press submit I get this error: 当我选择选项并按提交时,出现此错误:
TypeError: display_this is not a function
When I refresh the page, it displays the data. 当我刷新页面时,它将显示数据。
My code: 我的代码:
<form id="form">
<select name="op" id="op">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input value="Submit" type="submit" id="submit">
</form>
My JSON data: 我的JSON数据:
[
{"key":"A","val":"apple"},
{"key":"A","val":"orange"},
{"key":"B","val":"carrot"},
{"key":"B","val":"onion"}
]
My jQuery code: 我的jQuery代码:
$(document).ready(function () {
var output;
var display_this = function () {
var val = $("#op").val();
$.ajax({
async: 'false',
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (response) {
var data = JSON.stringify(response);
var resp = JSON.parse(data);
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
return results.html(output);
}
});
}();
$('#form').submit(function (e) {
e.preventDefault();
display_this();
});
});
You function is not available to your form submit. 您的功能不适用于您的表单提交。 I suggest this 我建议这个
$(function () {
$('#form').submit(function (e) {
e.preventDefault();
var output;
var val = $("#op").val();
$.ajax({
// async: 'false', // do NOT use async false
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (resp) {
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
$("#results").html(output);
}
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.