本文介绍了在触发器上传递json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在调用返回json数据的服务。I am calling a service that return json data.脚本:$.ajax({ type: "POST", url: "/some/service", dataType: "json", success: function(response) { if (response.status == "ok" && response.messages.length > 0) { // obj is a jQuery object obj.trigger(SOME_EVENT, response.messages); } }});这是回复示例:{ "status":"ok", "messages":[ {"id":1,"message_text":"latihan"}, {"id":123,"message_text":"hello"}]}当obj收到SOME_EVENT触发器时,我希望它传递下面的消息数据:when obj received the SOME_EVENT trigger, I am expecting it to pass messages data below:[{"id":1,"message_text":"latihan"}, {"id":123,"message_text":"hello"}]但当我将消息参数打印到控制台时,but when I printed messages parameter to console, // on receiving messagesobj.bind(SOME_EVENT, function(sender, messages) { console.log(messages);});结果,它只传递了下面的最后一条消息turn out, it only passed the last message below{"id":123,"message_text":"hello"}任何人都可以解释为什么我的自定义事件没有传递消息数组?anyone can explain why the array of messages is not passed by my custom event?推荐答案来自 http://docs.jquery.com/Events/trigger , trigger function是一个附加参数数组(在事件对象之后传递)。From http://docs.jquery.com/Events/trigger, the second parameter to the trigger function is an array of additional arguments (passed after the event object). response.messages property是一个数组,所以它们实际上作为单独的参数传递给你的处理程序:The value of your response.messages property is an array, so they are actually passed along to your handler as separate arguments:obj.bind(SOME_EVENT, function(sender, message1, message2/*, etc*/) { console.log(message1); // {"id":1,"message_text":"latihan"} console.log(message2); // {"id":123,"message_text":"hello"}});您可以将它们作为一个数组干净地收集:You can collect them cleanly as one array with:obj.bind(SOME_EVENT, function(sender) { var messages = Array.prototype.slice.call(arguments, 1); console.log(messages); // [{"id":1,"message_text":"latihan"}, // {"id":123,"message_text":"hello"}]}); 这篇关于在触发器上传递json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 12:38