getJSON callback function not getting called in a js file
In portlets, I have a JSP page where I have declared a resourceURL and mapped it to a Java class which has an overriden serveResource method.
<portlet:resourceURL var="myURL" >
<portlet:param name="dataType" value="VOICE" />
</portlet:resourceURL>
I have a javascript in a js file whic开发者_开发知识库n in turn fires an ajax call like this
$.getJSON(URL,{operator : 'XYZ'},function(b) {
//mycode
})
This js is imported into the jsp . Now when I click on the link, it triggers the javascript, the ajax call also goes through fine and request is passed to the java class. But the response is not coming back to the callback function. What I suspect is since this is in a seperate js file, the response is going to the jsp page and not to the callback function inside the js file. This exact same code works if I put it as inline script in the jsp.But I need to place the javascript code in a seperate js file and make it work. Is there a way to pass some context information when I fire getJSON ?.. is there a way to accomplish this ?
To begin with, check your URL in your javascript so it contains the parameter "jsoncallback=?".
$.getJSON('http://mysite.com/my.jsp?jsoncallback=?',
{operator : 'XYZ'},function(b) {
//mycode
})
jQuery will substitute the last questionmark, after the jsoncallback parameter, with an ID.
This ID will then be used on server side, in your JSP, to create a response that will start with a function named from the ID value.
Simple JSP example:
<%@ page language="java" contentType="application/json" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%
PrintWriter writer = response.getWriter();
String callback = request.getParameter("jsoncallback");
if (callback != null && callback.length() > 1)
{
writer.write(callback + "({ \"mykey\" : \"myvalue\" });");
}
%>
That would result in a response that would look something like this:
jQuery16205149872086476535_1314088378455({ "mykey" : "myvalue" });
So in a short answer, if your json response is NOT wrapped in this function name the callback function will not fire, instead you will get an error which you could see this way:
$.getJSON(URL,{operator : 'XYZ'},function(b) {
//mycode
}).error(function(jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + " errorThrown: " + errorThrown);
})
Hope this helps
Patrik
精彩评论