首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从XMLHttpRequest响应加载HTML

从XMLHttpRequest响应加载HTML
EN

Stack Overflow用户
提问于 2017-10-28 14:45:55
回答 1查看 1.3K关注 0票数 1

我正在从json文件中加载document.ready()上的表,如下所示

文件装载..。

代码语言:javascript
运行
复制
$(document).ready(function () {
        getSummaryData(function (data1) {
            var dataarray=new Array();
            dataarray.push(data1);


            $('#summaryTable').DataTable({
                data: dataarray,
                "columns": [
               ---
               ---

并从文件中检索数据,如下所示

代码语言:javascript
运行
复制
    function getSummaryData(cb_func1) {
    $.ajax({
        url: "data/summary.json",
        success: cb_func1
    });
    console.log(cb_func1)
}

这实际上是加载虚拟数据,这样我就可以知道如何正确加载表等等。

它执行以下操作: 1页加载2.从文件3读取数据.填充表

实际上,数据将不会从文件中加载,而是将从xhr响应返回,但我无法弄清楚如何将其连接到一起。用例是

  1. 通过XMLHttpRequest发布文件
  2. 得到响应
  3. 填充表(与文件相同的数据格式)

我会按以下方式发布文件..。

代码语言:javascript
运行
复制
<script>
    var form = document.getElementById('form');
    var fileSelect = document.getElementById('select');
    var uploadButton = document.getElementById('upload');

    ---
    form.onsubmit = function(event) {
        event.preventDefault();
    ---
---
 var xhr = new XMLHttpRequest();

 // Open the connection.  
 xhr.open('POST', 'localhost/uploader', true);      

  // handler on response
    xhr.onload = function () {
        if (xhr.status === 200) {

            console.log("resp: "+xhr);
            console.log("resptxt: "+xhr.responseText);

            //somehow load table with xhr.responseText

        } else {
            alert('ooops');
        }
    };

    // Send the Data.
    xhr.send(formData);

因此,理想情况下,我需要表中的一个空行或类似的行,直到有人上传了一个文件,然后将表填充到响应中。

任何帮助都很感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-28 14:52:45

代码语言:javascript
运行
复制
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "youruploadserver.com/whatever", true);
xhr1.onreadystatechange = function() {
    if (this.status == 200 && this.readyState == 4) {
        console.log(this.responseText);
        dostuff = this.responseText;
  };//end onreadystate
 xhr1.send();

它看起来基本上是正确的,你想要this.readyState == 4在那里。您的问题是什么,如何从响应中填充表?这还取决于您将如何发送数据,以及服务器将如何解析数据,看起来您希望使用一种智能的json格式。在发送JSON.stringify(formdata)之前,请确保您的服务器使用body解析器将其解析为json对象,具体取决于您使用的服务器。然后JSON.stringify()对象将其发回。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46990956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档