我正在创建一个页面,在提交表单时加载JSON文件。该表单在提交,search(this)
上调用javascript函数,该函数加载JSON文件并执行其他一些操作。为了测试一下,我使用jQuery documentation中的$.getJSON()
示例。
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
当我在我的javascript文件中的函数外部使用此代码时,它可以正常工作,但是如果我把它放在我的search
函数中,它就不会做任何事情。
发生了什么事?
在文本字段中输入一个字符串,然后按下搜索按钮。这将调用search
函数。搜索功能中的断点将显示它被调用,但新元素不会添加到页面中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Demo </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="LoadDemo.js"></script>
</head>
<body>
<h1> Demo </h1>
<form onsubmit="return search(this);">
<input type="text" name="query" id="query"> <input type="submit" value="Search">
</form>
<br>
<div id="results">
</div>
</body>
</html>
function search(form){
//Clear any existing elements from results
//$('#results').empty();
//Retrieve new results
queryStr = $("#query").val();
//If I put a breakpoint after this line, I can see the query string printed on the console
console.log(queryStr);
//This doesn't work
$.getJSON( "test.json", function( data ) {
console.log("success");
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
}
//This works
/*
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
}); /**/
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}