我正在尝试制作jquery 1.9.1 ajax + icanhaz / mustache的工作示例。这是我的模板:
<script id="user" type="text/html">
{{#users}}<li>Username: {{ username }}, fullname: {{ fullname }}</li>{{/users}}
</script>
这是我的javascript:
$(document).ready( function() {
$("#user-btn").click(function() {
$.ajax({
type: "GET",
url: "../php/client/json.php",
data: {
type: "users"
}
}).done(function( response ) {
var element = $('#dialog-message');
element.html("<ul>");
element.append(ich.user(response));
element.append("</ul>");
});
});
来自此地址的AJAX响应类似于:
{"users":[{"username":"jd","fullname":"John Doe"},{"username":"jl","fullname":"John Lennon"}]};
使用以下代码,icanhaz无法为我渲染任何内容。我花了一些时间在javascript控制台上,发现typeof response
是string
,我期待object
。 Icanhaz也期望对象 - 这就是为什么它无法呈现正确的响应。
我做错了什么,或者我只是一个不知道jquery.ajax总是返回字符串响应的可怜的新手?如果是这样,我应该如何处理它们?
答案 0 :(得分:11)
如果您从AJAX通话中收到string
,则需要添加dataType: "json"
。这将使jQuery在可能的情况下将响应解析为JSON。
$(document).ready( function() {
$("#user-btn").click(function() {
$.ajax({
type: "GET",
url: "../php/client/json.php",
data: {
type: "users"
},
dataType: "json"
}).done(function( response ) {
...
});
});
您确定ich.user
方法需要一组用户而不只是一个用户对象吗?
答案 1 :(得分:2)
为dataType: "json"
尝试选项$.ajax
。
答案 2 :(得分:2)
修改点击功能:
$("#user-btn").click(function () {
$.ajax({
type: "GET",
url: "../php/client/json.php",
data: {
type: "users"
},
dataType: 'json',
success: function (data) {
// Your code...
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});
});