使用JSONP获取跨域请求获取“意外标识符”

时间:2013-08-21 07:38:19

标签: extjs extjs4 jsonp

以下是我的尝试:

在客户端:

Ext.data.JsonP.request({
    url: "http://172.24.87.38:9090/DynamicWeb/hello-world",
    params: {
    },
    callback: function (result) {
        console.log(result);
        if (response.success === true) {
            Ext.Msg.alert('Link Shortened', response.result, Ext.emptyFn);
        } else {
            Ext.Msg.alert('Error', response.result, Ext.emptyFn);
        }
    }
});

在其他域(服务器端):

公共类HelloWorldServlet扩展了HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    /*resp.setContentType("text/html");

    PrintWriter out = resp.getWriter();
    out.print("Hello World from Servlet");
    out.flush();
    out.close();*/
    boolean jsonP=false;
    String cd=req.getParameter("callback");
    String n= "{data:Hello World from Servlet}";        
    if (cd!=null) {
        jsonP=true;
        resp.setContentType("text/javascript");
    } else {
        resp.setContentType("application/x-json");
    }
    Writer out=resp.getWriter();
    out.write(n);
}
}

我收到错误:

  

未捕获的SyntaxError:意外的标识符

{data:来自Servlet的Hello World}

  

我没有得到我错的地方。请帮我解决这个问题。感谢任何帮助。谢谢

2 个答案:

答案 0 :(得分:2)

String n= '{"data":"Hello World from Servlet"}';

答案 1 :(得分:0)

callback: function (result) { // you are stating you recieve result
        console.log(result);
        if (response.success === true) { // but you are trying to use response, change both to result or response
            Ext.Msg.alert('Link Shortened', response.result, Ext.emptyFn);
        } else {
            Ext.Msg.alert('Error', response.result, Ext.emptyFn);
        }
    }

你返回的json似乎也错了,试试:

callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });"; // where callback is the parameter sent via url