Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用javascrip将响应XMLHttpRequest转换为JSON,但对象为空_Javascript_Javascript Objects - Fatal编程技术网

Javascript 使用javascrip将响应XMLHttpRequest转换为JSON,但对象为空

Javascript 使用javascrip将响应XMLHttpRequest转换为JSON,但对象为空,javascript,javascript-objects,Javascript,Javascript Objects,我是一个Javascript新手,现在我有一个问题,那就是如何使用JSON.parse(response) 所以我的问题是 我确实使用XMLHttpRequest将文件加载到本地目录nameProject/app/resources/,并使用此代码 用于创建请求的代码 function readResourcesFile(pathFile, callback) { let confFile = new XMLHttpRequest(); confFile.open('GET', path

我是一个Javascript新手,现在我有一个问题,那就是如何使用
JSON.parse(response)

所以我的问题是

我确实使用
XMLHttpRequest
将文件加载到本地目录
nameProject/app/resources/
,并使用此代码

用于创建请求的代码

function readResourcesFile(pathFile, callback) {
  let confFile = new XMLHttpRequest();
  confFile.open('GET', pathFile, true);
  confFile.setRequestHeader('Content-Type', 'application/json');
  let configuration;
  confFile.onreadystatechange = function(){
    if (confFile.readyState === 4) {  // document is ready to parse.
      if (confFile.status === 200) {  // file is found
        let response = confFile.responseText;
        callback(response);
      }
    }
  };
  confFile.send(null);
}
这是我最后的请求

function readAllBenchmark() {
  readResourcesFile(rootPath + 'conf/benchmark-conf.json', function (configuration) {
    let objectConf = JSON.parse(configuration);
    console.debug('Configuration object');
    console.debug(objectConf);
    let files = objectConf.files;
    for(let i = 0; i < files.length; i++){
      console.debug('Road this file: ' + files[i]);
      readResourcesFile(rootPath + 'benchmark/' + files[i].toString(), function (fileBenchmark) {
        console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark);
        let objectBenchmark = JSON.parse(fileBenchmark);
        console.log('The object benchmark' + objectBenchmark);
        let newData = {
          label: files[i].split('.')[0],
          data: [
            convertNenosecondToSecond(objectBenchmark.benchmarks[0]), convertNenosecondToSecond(objectBenchmark.benchmarks[1])
          ],
          backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            'rgba(54, 162, 235, 0.2)',
          ],
          borderColor: [
            'rgba(54, 162, 235, 1)',
            'rgba(54, 162, 235, 1)',
          ],
          borderWidth: 2
        };
        addDataToChart(chartBenchmark, ['JSON', 'GraphTx'], newData);
      });
    }
  });
}
如果运行此代码,为什么我的代码可以工作

console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark);
还有这个没有

let objectBenchmark = JSON.parse(fileBenchmark);
更新代码并使用对象 函数readResourcesFileFetch(路径文件){ 返回fetch(路径文件{ 方法:'GET'、//*GET、POST、PUT、DELETE等。 缓存:“无缓存”,//*默认值,无缓存,重新加载,强制缓存,仅当缓存时 标题:{ “内容类型”:“应用程序/json”, //“内容类型”:“应用程序/x-www-form-urlencoded”, }, 推荐人:'无推荐人',//无推荐人,*客户 //body:JSON.stringify(data),//body数据类型必须与“Content type”头匹配 }) .then(response=>response.json());//将json响应解析为本机JavaScript对象 } 函数readAllBenchmarkFetch(){ 让configuration=readResourcesFileFetch(rootPath+'conf/benchmark-conf.json'); 然后(函数(confFile){ console.log(confFile); 让files=confFile.files; for(设i=0;i当您编写
控制台.log(someobject)
时,浏览器很聪明,请记住您正在记录一个对象,因此您将在控制台中看到一个对象。
编写
console.log(“Object is”+someobject)
时,JavaScript引擎将对象转换为字符串,并将结果追加到文本
对象之后。而字符串化对象确实会在默认情况下导致
[object object]

您可以尝试的一种解决方法是使用
而不是
+
,这会导致两个日志彼此相邻:

var someobject={};
log(someobject);
log(“Someobject是”+Someobject);

log(“Someobject:,Someobject”)如果您正在编写新代码,您应该查看att而不是非常旧的XMLHttpRequest。@感谢您的回答,我也有同样的错误,我已经在我的问题
fileBenchmark
中使用fetch更新了代码,应该已经将其解析为一个对象。你不需要再次解析它。我没有浏览那么聪明,谢谢你的帮助
let objectBenchmark = JSON.parse(fileBenchmark);
function readResourcesFileFetch(pathFile) {
    return fetch(pathFile, {
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      headers: {
        'Content-Type': 'application/json',
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      referrer: 'no-referrer', // no-referrer, *client
     // body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
      .then(response => response.json()); // parses JSON response into native JavaScript objects
}


function readAllBenchmarkFetch() {
  let configuration = readResourcesFileFetch(rootPath + 'conf/benchmark-conf.json');
  configuration.then(function (confFile) {
    console.log(confFile);
    let files = confFile.files;
    for(let i = 0; i < files.length; i++){
      console.debug('Road this file: ' + files[i]);
      let singleBenchmark = readResourcesFileFetch(rootPath + 'benchmark/' + files[i].toString());
      singleBenchmark.then(function (fileBenchmark) {
        console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark.toString());
        let newData = {
          label: files[i].split('.')[0],
          data: [
            convertNenosecondToSecond(fileBenchmark.benchmarks[0]), convertNenosecondToSecond(fileBenchmark.benchmarks[1])
          ],
          backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            'rgba(54, 162, 235, 0.2)',
          ],
          borderColor: [
            'rgba(54, 162, 235, 1)',
            'rgba(54, 162, 235, 1)',
          ],
          borderWidth: 2
        };
        addDataToChart(chartBenchmark, ['JSON', 'GraphTx'], newData);
      });
    }
  })
}