javascript - 在 javascript 中模仿 jsonp

标签 javascript php jquery

<script>
  window.addEventListener('load',function(){
    var unique_code="3412313ad"// Initialize it with the unique code provided to you.
    var param1="1"; // Initialize this with the value that you wish to see.For example 1 for navbar display , 2 for the side floating pop up
                  //while 3 for a transparent overlay on the whole page.
    var domain=window.location.hostname;// current domain.
    function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
    delete window[callbackName];
    document.body.removeChild(script);
    callback(data);
    };
    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
    script.onerror=function(){
      alert("failed to load snippet!");
    }
    }

    jsonp('http://localhost/server.php?unique_code='+unique_code+'&domain='+domain, function(data) {
      alert(data);
    if(data.status=='success'){
      alert('success');
    }else alert(data.reason);
    });
  });
</script>

这是一段模仿jquery的jsonp从远程服务器获取脚本的代码。

我使用了这个问题中给出的答案JavaScript XMLHttpRequest using JsonP

服务器端代码为

if(isset($_GET['unique_code']) && !empty($_GET['unique_code']) && isset($_GET['domain']) && !empty($_GET['domain'])){
  $unique_code=$_GET['unique_code'];
  $domain=$_GET['domain'];

  $statement=$mysqli->prepare('select * from `snippet_users` where unique_code=? AND domain=?');
  $statement->bind_param('ss',$unique_code,$domain);
  if(!$statement->execute())
     die(json_encode(array('status'=>'error','reason'=>'Server error.')));
  $result=$statement->get_result();

  if(mysqli_num_rows($result)>0)
      die (json_encode(array('status'=>'success')));
  else die(json_encode(array('status'=>'error','reason'=>'Unique code/Domain error.')));
}else{
  die(json_encode(array('status'=>'error','reason'=>'Unique code/Domain error.')));
}

一切都工作得很好,但我在控制台中看到错误,有点像这样:

enter image description here

我的解决方案是什么,这样我就不会收到此错误,并且我可以在警报框中获取数据?

最佳答案

您正在输出 application/json 而不是 application/javascript,因此您的浏览器认为它无效。 json 应该在函数调用中(回调参数)。但是,回调参数应该在服务器端进行验证,以防止 xss 注入(inject):

Is it necessary to validate or escape the jsonp callback string

关于javascript - 在 javascript 中模仿 jsonp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42320185/

相关文章:

javascript - 如何对所有分页项目应用过滤器并仅显示过滤后的项目?

javascript - jQuery 元素创建中的错误?

php - 如何保护隐藏字段数据不被更改

php - Wordpress 插件添加页面前端

php - 传递 PHP 变量时,Javascript 抛出 TypeError、document.getElementById

javascript - 使用 javascript 回显 css style.overflow 属性

javascript - 检查两个对象之间的键是否匹配的最简单方法是什么?

javascript - 范围的每 2 个分区循环 2

jquery - 想要使用jquery淡入淡出效果,但想要使用可见性:hidden initially

jQuery UI slider 与 Mootools.fx 幻灯片冲突