[英]Can't parse JSON data structure in JavaScript
How do pass back values to a form that was posted to the server using Ajax?如何将值传递回使用 Ajax 发布到服务器的表单?
In the view (shown below), I am just returning a simple data structure to test things:在视图中(如下所示),我只是返回一个简单的数据结构来测试事物:
def detail(request, widget_id):
widget = get_object_or_404(Widget, pk=widget_id)
if request.method == 'POST':
form = WidgetDetailsForm(request.POST, instance=widget)
if form.is_valid():
form.save()
return HttpResponseRedirect(request.path) # Redirect after POST
else:
if request.is_ajax():
response_dict = {
'page': 1,
'total': 2,
'rows': 3
}
json = simplejson.dumps(response_dict)
return HttpResponse( json, mimetype='application/json')
else:
form = WidgetDetailsForm(instance=widget)
params = {}
params['widget'] = widget
params['form'] = form
return render_to_response('widgets/detail.html', params,
context_instance=RequestContext(request))
The JavaScript in the template is:模板中的JavaScript为:
<script type="text/javascript">
/* <![CDATA[ */
// Wait for the DOM to be loaded
$(document).ready(function() {
// Bind 'myForm' and provide a simple callback function.
$('#updateform').wl_Form({
onSuccess: function(data, status){
alert(data);
alert(data.page);
alert(data.rows);
alert(data.total);
},
"status": false,
"confirmSend": false
});
});
/* ]]> */
</script>
I get the following from the alert statements.我从警报语句中得到以下信息。
{"rows": 3, "total": 2, "page": 1}
undefined
undefined
undefined
Why does data.page
, data.rows
, and data.total
return undefined?为什么data.page
、 data.rows
和data.total
返回 undefined?
Because data
is a string (of JSON) - note the output of your first alert()
.因为data
是一个字符串(JSON) - 请注意您的第一个alert()
的 output 。
Try something like:尝试类似:
$('#updateform').wl_Form({
onSuccess: function(response, status){
var data = $.parseJSON(response);
alert(data);
alert(data.page);
//...
}
});
Maybe do也许做
data = JSON.parse(data);
and dont forget do include json2.js
for older browsers?并且不要忘记为旧版浏览器包含json2.js
吗?
It depends on what wl_Form
does.这取决于wl_Form
的作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.