简单的 jQuery、PHP 和 JSONP 示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6809053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:19:39  来源:igfitidea点击:

Simple jQuery, PHP and JSONP example?

phpjqueryajaxjsonjsonp

提问by Jeff

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.

我面临着同源策略问题,通过研究该主题,我发现我的特定项目的最佳方法是使用 JSONP 进行跨域请求。

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

我一直在阅读IBM 关于 JSONP 的这篇文章,但是我并不是 100% 清楚发生了什么。

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>PHP JSONP 请求(或任何可能的术语;)) - 像这样(显然它是不正确的,它只是为了让您了解我想要实现的目标:) ):

jQuery:

jQuery:

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

PHP:

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?

我将如何将其转换为正确的 JSONP 请求?如果我将 HTML 存储在要返回的结果中,那也行吗?

回答by Liam Bailey

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

当您在外部域上使用 $.getJSON 时,它会自动执行 JSONP 请求,例如这里的推文滑块

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

如果您查看源代码,您会发现我正在使用 .getJSON 调用 Twitter API。

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

所以你的例子是:这已经过测试并且有效(你可以去http://smallcoders.com/javascriptdevenvironment.html查看它的实际效果)

//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

注意 ?callback=? 和 +res.fullname

回答by Ewout Kleinsmann

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

首先,您不能使用 JSONP 发出 POST 请求。

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

基本上发生的是动态插入脚本标记以加载您的数据。因此只有 GET 请求是可能的。

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.

整个过程由 jQuery 为您自动化。只是在外部域上使用 $.getJSON 并不总是有效。我可以从个人经历中说出来。

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

最好的办法是添加 &callback=? 给你网址。

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

在服务器端,您必须确保您的数据包含在此回调函数中。

ie.

IE。

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

EDIT:

编辑:

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

没有足够的代表对 Liam 的回答发表评论,因此这里的解决方案。

Replace Liam's line

替换利亚姆的线路

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

with

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

回答by Meni Samet

More Suggestion

更多建议

JavaScript:

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回调:

<?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).")";

}
?>

回答by mckoch

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

要使服务器使用有效的 JSONP 数组进行响应,请将 JSON 括在方括号中()并预先添加callback

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

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

使用json_encode()会将原生 PHP 数组转换为 JSON:

$array = array(
    'fullname' => 'Jeff Hansen',
    'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

回答by Mayur S

Simple jQuery, PHP and JSONP example is below:

简单的 jQuery、PHP 和 JSONP 示例如下:

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>

回答by user4000483

$.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) . ');';  
}

回答by Atul Sharma

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.

用于$data['elemname']访问值。

send jsonp request with JSON Object.

使用 JSON 对象发送 jsonp 请求。

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);
    }
})