Xhr multiple request javascript

Xhr multiple request javascript

本文关键字:javascript request multiple Xhr      更新时间:2023-11-27

我正在使用以下脚本从html请求中读取信息。

function runSearch(searchid, fullMovie) {    
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        var fullMovie = JSON.parse(xhr.responseText);
        var movie = { title: fullMovie.Title, runtime: fullMovie.Runtime, plot: fullMovie.Plot };
        document.getElementById('Title').innerText = movie.title;
        document.getElementById('Runtime').innerText = movie.runtime;
        document.getElementById('Plot').innerText = movie.plot
    }
};
    xhr.open('GET', 'http://www.omdbapi.com/?i=' +searchid+ '&plot=short&r=json', true);
    xhr.send(null);
}

如何将xhr.open中的searchid更改为使用div标记中的id="searchid"

<div>
<div id="tt0110912">
    <h1 id="Title">Title from tt00110912</h1>
    <p id="Runtime">Runtime from id</p>
    <p id="Plot">Plot from id</p>
</div>
</div>
   <br>
<div>
<div id="tt3322364">
   <h1 id="Title">Title from tt3322364</h1>
   <p id="Runtime">Runtime from id</p>
   <p id="Plot">Plot from id`enter code here`</p>
</div>
</div>

是否可以使用不同的xhr请求多次运行此脚本?如果可能的话,我该怎么做?

编辑:无法使代码工作!理论上,我需要代码根据div id类发出xhr请求,并用该id的xhr响应填充该div内的信息。想象一个电影数据库,它将显示电影列表中的特定电影信息。

将代码封装到函数中,然后使用不同的searchid值在循环中或手动多次调用它。

function runSearch(searchid, fullMovie) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            var fullMovie = JSON.parse(xhr.responseText);
            var movie = { title: fullMovie.Title, runtime: fullMovie.Runtime, plot: fullMovie.Plot };
            document.getElementById('Title').innerText = movie.title;
            document.getElementById('Runtime').innerText = movie.runtime;
            document.getElementById('Plot').innerText = movie.plot
        }
    };
    xhr.open('GET', 'http://www.omdbapi.com/?i=' + searchid + '&plot=short&r=json', true);
    xhr.send(null);
}

然后这样称呼它:

runSearch('your search id', fullMovie);

<div id="runSearch('tt0110912', fullMovie)">

JavaScript需要进入脚本元素(或内部事件属性,但它们很糟糕,应该避免)。

id属性用于放置元素的标识符。它不是JavaScript,把JavaScript放在那里毫无意义。

<script>
runSearch('tt0110912', fullMovie)
</script>

您的HTML无效。id在文档中必须是唯一的。不能在同一文档中重用if Title(etc)。改为使用类。