繁体   English   中英

如何在 Javascript 中使用 file_get_contents 和 json_decode

[英]How to use file_get_contents and json_decode in Javascript

我正在尝试在 Javascript 中使用这个 PHP API。 如何在 Javascript 中使用 file_get_contents 和 json_decode?

PHP API 代码

$content=@file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array 

if(!$url["error"]){  // If there is no error
 echo $url["short"]; //Outputs the short url 
}else{  
 echo $url["msg"]; //Outputs the error message 
}

Javascript

(function( $ ) {
  $(document).ready(function() { 
    var url = window.location.href;
    var host =  window.location.hostname;
    var title = $('title').text();
    title = escape(title);

    var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
    var facebook = 'http://www.facebook.com/sharer.php?u='+url;

    var tbar = '<div id="sicons">';
    tbar += '<a href="'+twitter+'" id="twitter" title="Share on twitter">Twitter</a>';
    tbar += '<a href="'+facebook+'" id="facebook" title="Share on Facebook">Facebook</a>';
    tbar += '</div>';

  });
})(jQuery);

编辑:感谢回复

数据.php

$content = @file_get_contents('http://doma.in/api.php?api=asd4sdf5634d&url=' . urlencode('http://' . $_SERVER['HTTP_HOST']  . $_SERVER['REQUEST_URI']));
echo $content;

我已将此添加到 Javascript 的顶部

$.getJSON('data.php', function(data) {
    if(!data.error){ // If there is no error
    alert(data.short) //Outputs the short url
    }else{
    alert(data.msg)
    }
});

Javascript 现在看起来像这样

(function( $ ) {
  $(document).ready(function() { 
    var shorturl = data.short;
    var title = $('title').text();
    title = escape(title);

    var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
    var facebook = 'http://www.facebook.com/sharer.php?u='+url;

    var tbar = '<div id="sicons">';
    tbar += '<a href="'+twitter+'" id="twitter" title="Share on twitter">Twitter</a>';
    tbar += '<a href="'+facebook+'" id="facebook" title="Share on Facebook">Facebook</a>';
    tbar += '</div>';

  });
})(jQuery);

我确定我做错了什么。 抱歉,我是编码初学者(C、C++)

通过 AJAX 加载数据是异步的。 您的第一个调用 ( $.getJSON ) 在页面加载后立即执行,但您作为参数传递的回调函数仅在基础 HTTP 请求完成后才执行。 这意味着你的程序不会阻塞等待 HTTP 请求; 在调用$.getJSON(...)之后,您的程序将继续运行,并且在 HTTP 请求完成后的某个时间调用回调方法。

加载页面后,您立即评估您的数据(在您的第二个函数中)。 但是,由于您的数据是异步加载的,因此在呈现文档并执行您的函数时尚未加载。

您的问题的解决方案是将评估数据的代码移动到$.getJSON(...)的回调函数中:

$.getJSON('data.php', function(data) {
    if (!data.error) {
        // Process your data here!
    } else {
        alert(data.msg)
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM