简体   繁体   English

如何使用javascript(和AJAX?)调用外部对象

[英]how to call an external object using javascript (and AJAX?)

First off, thanks to this community. 首先,感谢这个社区。 I'm slowly starting to understand this stuff and I appreciate all the feedback. 我正在慢慢开始理解这些内容,并感谢所有反馈。 That said, I come with another question. 也就是说,我还有另一个问题。

THE SITUATION: I'm trying to build a new site and I'm trying to use it as a learning experience to use some php and teach myself javascript (note, I'm wanting to stick with js right now and not jump to jquery until I get a better handle on js). 情况:我正在尝试建立一个新站点,并试图将其作为学习经验来使用一些php并自学javascript(注意,我现在想坚持使用js而不是跳转到jquery直到我对js有更好的了解)。 I've created a gallery that will have a series of thumbnails at the top that when clicked will populate a div below with artwork, its title and a description. 我创建了一个画廊,该画廊的顶部将具有一系列缩略图,单击这些缩略图将在下面的div中填充艺术品,其标题和说明。

THE SETUP: Because I want to have these called by names and not numbers (such as an array) so they can be interchangeable, I built each as an id's div containing all the components and then I'm calling it to the target location via the script: 设置:因为我想用名称而不是数字(例如数组)来调用它们,以便它们可以互换,所以我将每个都构建为包含所有组件的id的div,然后通过调用它到目标位置剧本:

function changeDiv(id) {
var target = document.getElementById('generic');
var id = document.getElementById(id);
target.innerHTML = id.innerHTML; 
}

In the body it looks like: 在体内看起来像:

<img src="images/thumbs/digital-art/thumb-space-oddity.jpg" id="thumb-space-odity" onclick="callDiv('space-oddity')"/>
...
<div class="gallery-frame" id="generic"></div>

Currently this works but since I have to have a place for all of the divs to be called from I've added a php include in the footer so it loads last but contains all of the images I could possibly need: 目前这有效,但是由于我必须要有一个位置才能调用所有div,因此我在页脚中添加了一个php include,因此它最后加载但包含我可能需要的所有图像:

<div style="display:none;">
<?php include("gallery.php"); ?>
</div>

... but from what I understand since this will still mean the page will load all the content that will really slow down the page. ...但是据我了解,因为这仍然意味着该页面将加载所有真正会使页面变慢的内容。 So I need a new solution. 所以我需要一个新的解决方案。

MY CHALLENGE: First off, is there a way to do this exclusively in javascript? 我的挑战:首先,有没有办法专门使用javascript执行此操作? If so I'd gladly do that! 如果是这样,我很乐意这样做!

Assuming I cannot, I have started looking into AJAX to see how it works and while it's starting to make nominal sense (still new to javascript so I only get half of it) and between w3schools.com and the stackoverflow topic I think i have a general idea of what I need to do but it's still not working. 假设我做不到,我已经开始研究AJAX的工作原理,并开始具有名义意义(对javascript来说还很陌生,所以我只得到其中的一半),而且在w3schools.com和stackoverflow主题之间,我认为我有一个我需要做什么的一般想法,但仍然无法正常工作。

THE PROBLEM: Based on the above stackoverflow comment I attempted to recreate the example function in my own instance and I have set it up as the following: 问题:基于以上stackoverflow注释,我尝试在自己的实例中重新创建示例函数,并将其设置为以下内容:

<script type="text/javascript">
function createXMLHttpRequest() {
    try {
        return new XMLHttpRequest();
    }
    catch (e)
    { alert('XMLHttpRequest not working'); }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    { alert('Msxml2.XMLHTT not working'); }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    { alert('Microsoft.XMLHTTP not working'); }
    alert("XMLHttpRequest not supported");
    return null;
}
function callDiv(id) {
    var xmlHttpReq = createXMLHttpRequest();
    var url = "gallery.asp?ID=" + id;
    xmlHttpReq.open("GET", url, true);
    xmlHttpReq.send();
}
</script>

From what I've read I left the first section alone as that sets up the function (removing the null and prompts as I don't need them) and trying to have the callDiv function run the same as the previous script I was using. 从我所读的内容中,我将第一部分留给我,因为那是对函数的设置(删除null和不需要的提示),并试图使callDiv函数的运行方式与我以前使用的脚本相同。 I have also saved out the gallery.php page as an .asp page but should I have left it as php? 我也已经将gallery.php页面另存为.asp页面,但是我应该将其保留为php吗?

Did it have to be .ashx? 一定是.ashx吗?

And since I don't know the file it was being called from I don't know what the '?REASON' that was used in the original example meant. 而且由于我不知道文件是从那里被调用的,所以我也不知道原始示例中使用的“?REASON”是什么意思。 I tried ?ID thinking I was telling it to look for an id. 我尝试了?ID,以为我告诉它要寻找一个ID。 Is that wrong, or unnecessary? 那是错误的还是不必要的?

Thanks! 谢谢!

-Chris -克里斯

Ok, good (and indeed brave) to want do do this in pure JS. 好吧,很高兴(而且确实很勇敢)想在纯JS中做到这一点。 It's a quirky, but fun language, honestly. 老实说,这是一种古怪但有趣的语言。 The easiest way to achieve your goals will be using ajax calls, though it isn't a necessity. 实现目标的最简单方法是使用ajax调用,尽管这不是必需的。
Looking at your code, your calls will probably work just fine but you've left out the most important part of it all: a callback for the onreadystatechange event 查看您的代码,您的调用可能会正常工作,但您忽略了其中最重要的部分: onreadystatechange事件的回调

As your script sends a request to the server, the state of that request is checked. 当脚本将请求发送到服务器时,将检查该请求的状态。 Once the server has finished processing the sent request and the has finished responding the readyState should be 4. (more info can be found here ). 服务器完成对发送的请求的处理并且完成对readyState的响应后,其状态应为4。(可在此处找到更多信息)。
Basically, try adding this to your ajax object: 基本上,尝试将其添加到您的ajax对象中:

function callDiv(id)
{
    var xmlHttpReq = createXMLHttpRequest();
    xmlHttpReq.onreadystatechange = function()
    {
        if (this.readyState === 4 && this.status === 200)
        {
            //this === xmlHttpReq, "this" can be tricky, it refers to the calling obj.
            console.log(this.responseText);//check your console, see what that tells you
        }
    };
    var url = "gallery.asp?ID=" + id;
    xmlHttpReq.open("GET", url, true);
    xmlHttpReq.send();
}

Personally, seeing as you're new to JS, I'd also suggest just preloading your images in a regular way: 就个人而言,看到您是JS的新手,我还建议您以常规方式预加载图像:

var nextImg = document.createElement('img');
nextImg.src = 'images/nextImage.jpg';
nextImg.onload = function()
{
    //targetId
    document.getElementById('wherever').appendChild(this);//this === nextImg
};

The last scenario creates a new DOM element, img, the source is set, so that the image is being loaded, when the loading has completed, there's an event handler that appends the new image to whatever container element (might as well be the document.body element) of your choice. 最后一种情况是创建一个新的DOM元素img,设置源,以便加载图像,当加载完成时,有一个事件处理程序会将新图像附加到任何容器元素(可能是文档) .body元素)。
the advantage here is that you don't have to wrestle with AJAX. 这样做的好处是您不必费解AJAX。 It's asynchronous nature can be tricky. 它的异步特性可能很棘手。 On a smal scale, this is also easily implemented and easy to debug. 在小规模上,这也易于实现且易于调试。 The downside: it's a nightmare to maintain, and shifts all functionality to the client side. 缺点:维护是一场噩梦,并将所有功能转移到客户端。 There's also a couple of more issues, but I'm a bit pissed and tired. 还有更多其他问题,但是我有点生气和疲倦。 read more here . 在这里阅读更多 If needs must, I'll have another look at this tomorrow. 如果需要,我明天再看一看。

Oh, yes: welcome to SO BTW. 哦,是的:欢迎来到SO BTW。

Ok, see the follow code, you execute the request inside callDiv , and the result go inside .foo element: 好的,请参见以下代码,在callDiv内执行请求,结果放入.foo元素内:

function callDiv(id) {
    var request;  // Store AJAX request

    // Here you verify browsers support, to create new Ajax request
    try { // Opera, Firefox and Safari support
        request = new XMLHttpRequest();
    } catch (e) { // IE support
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                // Hide error, something goes wrong
            }
        }
    }

    // Show result inside .foo div
    request.onreadystatechange = function() {
        if(request.readyState == 4) { // Success
            var element = document.getElementByClass('foo');
            element.innerHTML = request.responseText;
        }
    }

    // Here you send the request
    request.open("GET", "gallery.php?id=" + id, true);
    request.send(null); 
}

<div class='foo'><!-- HERE WILL SHOW THE AJAX RESULT --></div>

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

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