问题
I am trying to return an array of products using a get request. The response returns XML with a 200 request.
Web Service:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public List<product> GetAllProducts()
{
using (SchulteDesignYourOwnEntities db = new SchulteDesignYourOwnEntities())
{
return db.products.ToList();
}
}
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'http://www.organizeliving.com/designwebservice.asmx/GetAllProducts',
dataType: 'json',
success: function (result) {
alert("Result: " + result.length);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Status: " + xhr.status);
console.log("Message: " + thrownError);
}
});
});
</script>
</head>
<body></body>
</html>
回答1:
You have the dataType
as 'json'
. jQuery will automatically try to parse JSON from the response. If it cannot, it considers it an error.
XML is not valid JSON (it will really hate the opening <
). You can either change the dataType
to 'xml'
(or nothing) or actually emit pure JSON from the server instead.
来源:https://stackoverflow.com/questions/13726646/jquery-ajax-request-syntaxerror-unexpected-token