简体   繁体   English

JSONP回调函数无法正常工作

[英]JSONP callback function not working correctly

I have jsonp callback functionalty. 我有jsonp回调功能。 Response coming from server is undefined.I do not know where the problem is. 来自服务器的响应是不确定的。我不知道问题出在哪里。 I have made RND for jsonp. 我为jsonp制作了RND。 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 Servlet代码是

        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. 首先,当您想覆盖默认函数名称时,使用jsonpCallback 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. 给它一个返回undefined的函数只会破坏事情。

Remove the jsonpCallback property from your object . 从您的对象中删除jsonpCallback属性 Handle things in success . success处理事情。

Second, that servlet code is going to generate: 其次,该servlet代码将生成:

jQueryCallback23235(chaaaaapiio gya)

This isn't valid JavaScript. 这不是有效的JavaScript。 You need to have a real JavaScript data structure as your function arguments. 您需要具有真实的JavaScript数据结构作为函数参数。

Typically, a JSONP response would consist of an object literal: 通常,JSONP响应将由对象文字组成:

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. 找到一个用于生成JSON的Java库,并使用该库生成paren的内容,不要尝试手工编写JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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