简体   繁体   中英

JSONP callback function not working correctly

I have jsonp callback functionalty. Response coming from server is undefined.I do not know where the problem is. I have made RND for jsonp. I am posting code

$.ajax({
         url : 'http://192.168.16.111:8081/MiddleWareUsman/androidServlet', 
         type: "GET",
         dataType: "jsonp",         
         crossDomain: true,
         async: false,
         data : {"fname": "chaaaaapiio","lname": "gya"},            
         jsonpCallback:  function(data, status){
            alert('callback');
            alert(data);
         },            
         success: function(data, status){
            alert('sucess');
         },
     error : function(xhr, ajaxOptions, thrownError) {          
         alert(thrownError);                        
         }
  });

And Servlet code is

        String a=request.getParameter("fname");
        String b=request.getParameter("lname");
        String cb=request.getParameter("callback");     
        response.getWriter().write(cb+"("+a+" "+b+")");

First, jsonpCallback is used when you want to override the default function name. If you assign a function to it, then the return value of that function should be the name. Giving it a function that returns undefined is just going to break things.

Remove the jsonpCallback property from your object . Handle things in success .

Second, that servlet code is going to generate:

jQueryCallback23235(chaaaaapiio gya)

This isn't valid JavaScript. You need to have a real JavaScript data structure as your function arguments.

Typically, a JSONP response would consist of an object literal:

jQueryCallback23235({ "something": "chaaaaapiio", "something": "gya")

Find a Java library for generating JSON and use that to produce the contents of the parens, don't try to write JSON by hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM