通过JSON响应发送状态数据到POST - 通过JavaScript解析

问题描述:

我有一个用于上传文件的PHP代码,它工作正常,并且作为最终结果,我发送了JSON响应与上传状态,我无法检索。通过JSON响应发送状态数据到POST - 通过JavaScript解析

上传文件(POST)后,我的回应是这样的:

{"html_content":"<p>File was uploaded<\/p>"} 

PHP上传代码如下所示:

if (!is_file($targetFile)) { 
    move_uploaded_file($tempFile,$targetFile); 
    $html_content="<p>File was uploaded</p>"; 
} 
else { 
    $html_content="<p>You have uploaded duplicate.</p>"; 
    move_uploaded_file($tempFile,$targetFile); 
} 

$json_array=array('html_content'=>$html_content); 

header('Content-type: text/json'); 
header('Content-type: application/json'); 
echo json_encode($json_array); 

和JavaScript主代码获得显示消息:

this.on("success", function(file,responseText) { 
    $.ajax({ 
     dataType: 'json', 
     success: function (response) { 

      var htmlElement = document.createElement("div"); 
      htmlElement.setAttribute("class","success-message"); 
      var responseText = response.html_content; 
      var messageText = document.createTextNode(responseText); 
      htmlElement.appendChild(messageText); 
      file.previewTemplate.appendChild(htmlElement); 

      console.log(response.html_content); 
     } 
    }); 
}); 

当我从AJAX部分解开上面的JS并将变量responseText设置为stat集成电路一切正常。

还当我是不会使用AJAX,只是输出console.log(responseText);我在控制台收到此:

Object {html_content: "<p>File was uploaded</p>"}

任何线索我在我的情况下错过了什么?

+0

我不知道在php中定义Content-type头两次会导致浏览器无法解析数据。 –

好,知道了解决。 JavaScript代码看起来像

 this.on("success", function(file,responseText) { 

      str = JSON.stringify(responseText); 
      responseMessage = $.parseJSON(str); 

      var htmlElement = document.createElement("div"); 
      htmlElement.setAttribute("class","success-message"); 
      htmlElement.innerHTML = responseMessage.html_content; 
      file.previewTemplate.appendChild(htmlElement); 
     }); 

您没有向PHP服务器发送请求。指定网址参数。

$.ajax({url: "your_php_file", 
     dataType: 'json', 
     success: function (response) { 
        ... 
       } 
      }); 

甚至更​​好:

$.getJSON("your_php_file", function(data) { ... }); 
+0

我已经这样做了,但'response.html_content'被解析为'undefined'。我认为这是因为'your_php_file'已经在文件上传过程中执行过(并且当时也生成了JSON) – JackTheKnife

+0

我的猜测是你的PHP在发送JSON之前在某处发生了断裂。尝试删除上传逻辑,并首先从PHP返回JSON。 –

+0

正如我在OP中提到的 - PHP上传器代码工作正常。我可以上传文件并生成JSON作为每个上传文件的响应,但JavaScript部分没有获取正确的数据。国际海事组织我不应该检查JS的'your_php_file'作为已经执行,并返回JSON回浏览器,但简单得到这些返回的数据。直接调用'your_php_file'将不会返回任何文件,因为此时文件没有上传。 – JackTheKnife