1. 程式人生 > >ajax的跨域和非跨域請求

ajax的跨域和非跨域請求

非跨域請求

get請求

<button onclick="sedjson()">測試json資料</button>

<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function sedjson() {
   $.ajax({
      type:"GET",
      url:"s",    //s是SpringMVC中Controller中的請求地址 
      contentType:"application/json;charset=utf-8",
      success:function(data)
      {
         //因為獲取到的是一個數組,所以用陣列接收
         //注意要使用var初始化變數,用int不支援
         for(var i=0;i<data.length;i++)
         {
            alert(data[i].deptId+"  "+data[i].deptName);
         }           
      },
      error:function()
      {
         alert("解析失敗");
      } 
   });  
}

</script>

 

伺服器端Controller
 

   @RequestMapping("s")
   @ResponseBody
   public List<Department> showdepart()

   {
      return departmentService.showdepartment();     
   }

 

POST請求:


function fasongdata()
{
   $.ajax({
      type:"POST",
      url:"testdelete",
      //data:$('#form1').serialize(),//將提交表單序列化     
      //contentType:"application/json;charset=utf-8",
      data:{id:$("#id").val()},//傳入後臺資料
      success:function(data)
      {
         if(data.trim()=="success")
         {
            alert("成功");
         }
         else
         {
            alert("失敗");
         }      
      },
      error:function()
      {
         alert("解析失敗");
      }
   });  

}


​

表單:

<form id="form1" method="post">

要刪除的id:<input type="text" name="id" id="id">

<input type="button" value="刪除" id="btn" onclick="fasongdata()">

</form>

 

Controller中

@RequestMapping("testdelete")

@ResponseBody
public String testdelete(HttpServletRequest request,HttpServletResponse response)
{
      response.addHeader("Access-Control-Allow-Origin", "*");//允許ajax跨域請求
      response.setCharacterEncoding("utf-8");
      response.setContentType("text/html");
      int id=Integer.parseInt(request.getParameter("id"));
      int i=employeeService.deleteEmp(id);
      if (i>0) {
         return "success";
      }else
      {
        return "faile";
      }     
}

 

Ajax跨域請求:

Get請求

<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
        $(document).ready(function () {
         
            $("#btn").click(function () {
                $.ajax({
                    url: 'https://www.apiopen.top/journalismApi',
                    type: 'GET',
                    success: function (data) {               
                    //對於json資料有物件型別時可以用eval獲取返回值
                     var json=eval(data)           
                    //看清楚資料是Object型別還是Array型別
                       $(text).val(json.data.tech[0].title);                

                    }
                });
            });           
        });

</script>

<input id="btn" type="button" value="跨域獲取資料" />

<textarea id="text" style="width: 400px; height: 100px;"></textarea>

 

(在伺服器端要設定頭資訊,設定response,和request物件)

POST請求:

function fasongdata()

{
   $.ajax({
      type:"POST",
      url:"http://127.0.0.1:8080/hope/testdelete",
      //data:$('#form1').serialize(),//將提交表單序列化     
      //contentType:"application/json;charset=utf-8",
      data:{id:$("#id").val()},//傳入後臺資料
      success:function(data)
      {
         if(data.trim()=="success")
         {
            alert("成功");
         }
         else
         {
            alert("失敗");
         }        
      },
      error:function()
      {
         alert("解析失敗");
      }     

   });  

}

form表單:

<form id="form1" method="post">

要刪除的id:<input type="text" name="id" id="id">

<input type="button" value="刪除" id="btn" onclick="fasongdata()">

</form>

 

Controller中:
  

   @RequestMapping("testdelete")
   @ResponseBody
   public String testdelete(HttpServletRequest request,HttpServletResponse response)

   {
      response.addHeader("Access-Control-Allow-Origin", "*");//允許ajax跨域請求
      response.setCharacterEncoding("utf-8");
      response.setContentType("text/html");
      int id=Integer.parseInt(request.getParameter("id"));
      int i=employeeService.deleteEmp(id);
      if (i>0) {
         return "success";
      }
      else
      {
         return "faile";
      }     

   }