类似于php file_get_contents的Javascript方法

时间:2014-07-21 05:39:21

标签: javascript jquery

在javascript或jquery中是否有类似于file_getcontents的方法。

<?php  $html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt'); 
echo ($html);?>

这工作正常,但我不想使用PHP我想jquery或javascript我尝试过这种方法

$(document).ready(function () {

         $.ajax({
              url:"http://m.uploadedit.com/b037/1405919727889.txt",
              type: "Get",
              success: function (data) {
                   alert(data)
              }
           });
});

但我一无所获。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

你不能做跨域请求,你需要设置一个php代理,比如,在服务器上创建一个php文件说get_contents.php

$html = file_get_contents('http://m.uploadedit.com/b037/1405919727889.txt'); 
echo ($html);

并在jquery中,访问您的php,如下:

$(document).ready(function () {
    $.ajax({
        url:"http://your_server.com/get_contents.php",
        type: "GET",
        success: function (data) {
            alert(data)
        }
    });
});

答案 1 :(得分:0)

Javascript无法获取文件的内容,但正如您所见,php可以。我建议你使用togeter

$(document).ready(function () {    
    $.ajax({
        url:"http://m.uploadedit.com/content/somehash",
        type: "Get",
        success: function (data) {
            alert(data)
        }
    });
});

在&#39; / content / somehash&#39;把一个php文件:

<?php echo file_get_contents('http://m.uploadedit.com/content/somehash');

我建议你隐藏文件名的真实名称。如果您公开这样的信息,如果某些恶意用户尝试http://m.uploadedit.com/content/../../.htaccess(例如),您会期望什么?风险是提供太多信息。这不是一个好主意。


存在替代方案,其名称为NodeJs:

fs.readFile('/content/somehash', function (err, data) {
    if (err) throw err;
    // here you can output the content ...
});

答案 2 :(得分:0)

这是一个解决方案。我找到了这个并且工作正常

$( document ).ready(function() {
$.ajaxPrefilter(function(options) {
  if(options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
    //options.url = "http://cors.corsproxy.io/url=" + options.url;
  }
});

$.get(
    'http://m.uploadedit.com/b037/1405919727889.txt',
    function(response) {
        $("#content").html(response);
        alert(response);
});