$.ajax and $.getJson resolve cross-domain requests

WBOY
Release: 2016-08-08 09:30:13
Original
929 people have browsed it

When writing js, we always encounter the problem of cross-domain requests. Now we know two methods and record them:

1) Use $.ajax, but the return data type should be set to jsonp, example:

     $.ajax({
        type: 'get',
        contentType: "application/json; charset=utf-8",      
        url: "http://localhost:8080/aqi/getCityList.php",
        dataType: 'jsonp',
        headers: {
            Accept: "application/json",
            "Access-Control-Allow-Origin": "*"
        },
        crossDomain: true,
        async: false,
        jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
        jsonpCallback:"success_jsonpCallback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
        success:function(json){
          getCityListSuccess(json);
        },
        error: function (data, textStatus, errorThrown) {
            console.log("error" + ' ' + JSON.stringify(data) + textStatus + errorThrown);
        }
    });
Copy after login
The code on the PHP side is:
<?php
	header("Content-Type: text/html;charset=utf-8");
  	$db_name="aqidata.db";
	$conn = new sqlite3($db_name);
	$callback = $_GET[&#39;callback&#39;];
	$resultarray=array();
    <span style="white-space:pre">	</span>$sql = "select * from 'city' where 1=1 order by id";
    <span style="white-space:pre">	</span>$result = $conn->query($sql);
    <span style="white-space:pre">	</span>$i=0;
    <span style="white-space:pre">	</span>while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    	<span style="white-space:pre">	</span>$resultarray[$i]=$row;
	    <span style="white-space:pre">	</span>$i++;
    <span style="white-space:pre">	</span>}

	echo $callback.'('.json_encode($resultarray).')';


?>
Copy after login
Note: 1. The jsonp parameter must be specified in ajax, and then the backend must write the callback function name into the return value.

The blog post I refer to is: http://www.cnblogs.com/xcxc/p/3729660.html

2) Using $.getJSON, this function supports cross-domain calls.

     $.getJSON("http://localhost:8080/aqi/getCityList.php",function(json){
      getCityListSuccess(json);
     });
Copy after login
But the back-end code (php) must be added:
header("Access-Control-Allow-Origin:*");
Copy after login
otherwise an error will be reported:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 
Copy after login
The blog post I refer to is: http://blog.163.com/lvshutao@126/blog/static/164637467201442253942499/?latestBlog

The above introduces $.ajax and $.getJson to solve cross-domain requests, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!