Simple jQuery, PHP and JSONP example?

2018-12-31 18:50发布

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requests.

I've been reading this article from IBM about JSONP, however I am not 100% clear on what is going on.

All I am asking for here, is a simple jQuery>PHP JSONP request (or whatever the terminology may be ;) ) - something like this (obviously it is incorrect, its just so you can get an idea of what I am trying to achieve :) ):

jQuery:

$.post('http://MySite.com/MyHandler.php',{firstname:'Jeff'},function(res){
    alert('Your name is '+res);
});

PHP:

<?php
  $fname = $_POST['firstname'];
  if($fname=='Jeff')
  {
    echo 'Jeff Hansen';
  }
?>

How would I go about converting this into a proper JSONP request? And if I were to store HTML in the result to be returned, would that work too?

7条回答
高级女魔头
2楼-- · 2018-12-31 19:30

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:

echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";

Using json_encode() will convert a native PHP array into JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";
查看更多
笑指拈花
3楼-- · 2018-12-31 19:32
$.ajax({

        type:     "GET",
        url: '<?php echo Base_url("user/your function");?>',
        data: {name: mail},
        dataType: "jsonp",
        jsonp: 'callback',
        jsonpCallback: 'chekEmailTaken',
        success: function(msg){
    }
});
return true;

In controller:

public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';  
}
查看更多
倾城一夜雪
4楼-- · 2018-12-31 19:34

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

Note the ?callback=? and +res.fullname

查看更多
何处买醉
5楼-- · 2018-12-31 19:34

Simple jQuery, PHP and JSONP example is below:

window.onload = function(){
	$.ajax({
		cache: false,
		url: "https://jsonplaceholder.typicode.com/users/2",
		dataType: 'jsonp',
		type: 'GET',
		success: function(data){
			console.log('data', data)
		},
		error: function(data){
			console.log(data);
		}
	});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看更多
情到深处是孤独
6楼-- · 2018-12-31 19:34

Use this ..

    $str = rawurldecode($_SERVER['REQUEST_URI']);
    $arr = explode("{",$str);
    $arr1 = explode("}", $arr[1]);
    $jsS = '{'.$arr1[0].'}';
    $data = json_decode($jsS,true);

Now ..

use $data['elemname'] to access the values.

send jsonp request with JSON Object.

Request format :

$.ajax({
    method : 'POST',
    url : 'xxx.com',
    data : JSONDataObj, //Use JSON.stringfy before sending data
    dataType: 'jsonp',
    contentType: 'application/json; charset=utf-8',
    success : function(response){
      console.log(response);
    }
}) 
查看更多
初与友歌
7楼-- · 2018-12-31 19:43

More Suggestion

JavaScript:

$.ajax({
        url: "http://FullUrl",
        dataType: 'jsonp',
        success: function (data) {

            //Data from the server in the in the variable "data"
            //In the form of an array

        }

});

PHP CallBack:

<?php

$array = array(
     '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'),
     '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'),
);

if(isset ($_GET['callback']))
{
    header("Content-Type: application/json");

    echo $_GET['callback']."(".json_encode($array).")";

}
?>
查看更多
登录 后发表回答