问题
I'm using the $.ajax
function in JQuery to get JSON from a file. HTML, JavaScript and json files are in the same directory. The problem is that when i print the data returned from the success callback function it prints the HTML markup of the HTML page instead of the JSON.
Here is my data.json
file content:
{
"products":[
{
"skuNum":"SKU# 105423-2",
"brand":"nike running shoes",
"section":"men > shoe > Running shoes",
"img":"392232_004_ss_01.jpg",
"price":500
},
{
"skuNum":"SKU# 105423-2",
"brand":"south face jacket",
"section":"women > Apparel > jackets",
"img":"jacket.jpeg",
"price":800
}
]
}
my JQuery:
$(function () {
$.ajax({
type: 'GET',
URL:'data.json',
success:function (data) {
console.log(data);
},
error:function (error) {
console.log('error')
}
});
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="ajax.css">
<script src="jquery-3.3.1.js"></script>
</head>
<body>
<nav>
<a href="#">Home</a>
<a href="#" id="products">Products</a>
<a href="#">Help</a>
</nav>
<div class="container">
</div>
<script src="ajax.js"></script>
</body>
</html>
And here is a snippet of the output:
回答1:
Javascript is case sensitive. The correct property for URL
is url
in $.ajax
options object
When you provide an incorrectly spelled property it will get ignored and the proper property will return undefined.
In this case since it is URL
the request would get made to current page since no url
is available in the options
Change:
URL:'data.json',
To
url:'data.json',
来源:https://stackoverflow.com/questions/52189180/ajax-returns-the-html-code-of-current-page-instead-of-json