dpxpz37157 2013-02-03 08:05
浏览 47

使用php在javascript中读取URL内容

I want to read the content of a URL in javascript. The URL is not on my domain so I need a middle layer that can access cross domain. I tried to use a PHP function to read the URL and return the result to javascript using jquery but it didn't work.

Here is my trial:

I created a php file named "phpjs_test.php"

<?php
function get_data(){
  $url='http://asmary.dreameg.com/texttable.txt';
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  $content = curl_exec($ch);
  $content = htmlspecialchars($content);
  curl_close($ch);
  $content = nl2br($content);
  return $content;
}
?>

and this is the javascript code:

<script>
        $(document).ready(function () {
            //httpQuery("http://asmary.dreameg.com/texttable.txt");
            getOutput();
        });

        function getRequest() {
            var req = false;
            try {
                // most browsers
                req = new XMLHttpRequest();
            } catch (e) {
                // IE
                try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    // try an older version
                    try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        return false;
                    }
                }
            }
            return req;
        }

        function getOutput() {
            var ajax = getRequest();
            ajax.onreadystatechange = function() {
                if (ajax.readyState == 4) {
                    document.getElementById('output').innerHTML = ajax.responseText;
                }
            };
            ajax.open("GET", "phpjs_test.php", true);
            ajax.send(null);
        } 

I'm completely new to PHP so I don't know even the PHP function is correct or not.

  • 写回答

2条回答 默认 最新

  • dongtuo8170 2013-02-03 08:30
    关注

    You should just use jQuery ajax methods instead of creating XMLHTTPRequest you don't have to bother with adding more code for IE plus you're already loading the jQuery library. Also if you set the header to Allow-Origin-Access in your PHP file and specify the other domain you're requesting from then you can make an AJAX request and get the response otherwise it will return nothing or in your dev tools network tab it will show a 403 - Forbidden.

    Access-Control-Allow-Origin syntax

    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler