wap网站开发之解决Ajax跨域获取json数组的问题

最近在写一个 wap 网站,它是由服务器端提供一个接口,如:

http://192.168.1.122:8080/waptest1/indexImg.do

然后由在jsp页面中解析json数组并获得相应属性值。

等到了正式环境下我把 url 换成远程的 http://mobile.51bi.com/indexImg.do (见上传图片附件)

jsp 就访问不到数据了,我上网查了一下是 Ajax 跨域访问的问题。

解决:先通过 servlet 取出数据再交给 jsp,通过servlet中转了一下。

jsp代码:



<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



My JSP 'mlkindex.jsp' starting page


























****************************************************

servlet代码:

注: 此处亦可参照本人的这篇文章: http://chenzheng8975.iteye.com/blog/1602301

package mlk.test.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MlkIndexServlet extends HttpServlet {

/**
* The doGet method of the servlet.

*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
URL url = new URL("http://mobile.51bi.com/indexImg.do ");
InputStream is = url.openStream();
byte[] b = new byte[is.available()];
is.read(b);
String resultString=new String(b, "utf-8");
String tempString=new String(resultString.getBytes("iso-8859-1"),"utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
System.out.println(resultString);
out.print(resultString);
is.close();
}

/**
* The doPost method of the servlet.

*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

this.doGet(request, response);
}

}

你可能感兴趣的:(wap,Ajax跨域,json数组,wap)