ajax,php,jsp,ajax跨域调用

来源:互联网 发布:淘宝用花呗付款好吗 编辑:程序博客网 时间:2024/06/16 15:43

php 页面程序:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
 <script src="jquery-2.1.1.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function(){
         $.ajax({ 
                url: 'http://localhost:8080/webtt/index3.jsp', 
                type: 'get', 
                dataType: 'jsonp', 
                jsonpCallback:'success_jsonpCallback', 
                data: { 
                    username: 'chenchao' 
                }, 
                success: function (json) { 
                   alert(json); 
      //alert(json.name);
      $.each(json, function(index,value){
                  alert(json[index].firstName);
      });
 
                }, 
                error : function(XMLHttpRequest, textStatus, errorThrown){ 
                   alert(textStatus); 
                } 
            }); 
    });

function ajax_sun(){
 $.ajax({ 
                url: 'http://localhost:8080/webtt/index3.jsp', 
                type: 'get', 
                dataType: 'jsonp', 
                jsonpCallback:'success_jsonpCallback', 
                data: { 
                    username: 'chenchao' 
                }, 
                success: function (json) { 
                   alert(json); 
      //alert(json.name);
      $.each(json, function(index,value){
                  alert(json[index].firstName);
      });
 
                }, 
                error : function(XMLHttpRequest, textStatus, errorThrown){ 
                   alert(textStatus); 
                } 
            }); 
 }
  
</script>
</head>

<body>
<input type="button" onclick="ajax_sun()" value="测试" />
<div id="res"></div>
 </body>
</html>

 

jsp页面程序:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% 
//获取Jquery自动生成的callback 函数名称
String callbackName = request.getParameter("callback");
String userName = request.getParameter("username");
//要返回的json格式数据
//String jsonData = "{\"name\":\"chenchao\"}";
String jsonData = "[{ \"firstName\": \""+userName+"\",\"lastName\":\"McLaughlin\", \"email\": \"aaaa\" }, { \"firstName\": \"孙忠海\",\"Hunter\":\"McLaughlin\", \"email\": \"bbbb\" }, { \"firstName\": \"Elliotte\",\"Harold\":\"McLaughlin\", \"email\": \"cccc\" }]" ;

//设置返回的数据类型
//response.setContentType("text/javascript;charset=gb2312");
//执行callback函数名称字符串
String jsonp = callbackName + "(" + jsonData + ")";
//返回输出
System.out.println(jsonp);
%>
<%=jsonp%>

 

1 0