Simple jQuery, PHP and JSONP example?

后端 未结 7 2183
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 16:36

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 requ

相关标签:
7条回答
  • 2020-11-22 16:52

    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).")";
    
    0 讨论(0)
  • 2020-11-22 16:55

    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>

    0 讨论(0)
  • 2020-11-22 16:56

    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

    0 讨论(0)
  • 2020-11-22 16:56

    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).")";
    
    }
    ?>
    
    0 讨论(0)
  • 2020-11-22 17:01
    $.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) . ');';  
    }
    
    0 讨论(0)
  • 2020-11-22 17:13

    First of all you can't make a POST request using JSONP.

    What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

    Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

    This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

    The best thing to do is adding &callback=? to you url.

    At the server side you've got to make sure that your data is wrapped in this callback function.

    ie.

    echo $_GET['callback'] . '(' . $data . ')';
    

    EDIT:

    Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

    Replace Liam's line

     echo "{'fullname' : 'Jeff Hansen'}";
    

    with

     echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';
    
    0 讨论(0)
提交回复
热议问题