简体   繁体   English

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

[英]Sending status data via JSON response to POST - parse via JavaScript

I have a PHP code for uploading files, which works fine, and as final outcome I have sent JSON response with uploading status which I'm not able to retrieve. 我有一个用于上传文件的PHP代码,效果很好,作为最终结果,我发送了带有无法上传的上传状态的JSON响应。

After uploading file (POST) my response looks like: 上传文件(POST)后,我的响应如下:

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

PHP uploader code looks like: 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);

and JavaScript main code to get message displayed: 和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);
        }
    });
});

When I will unwrap above JS from AJAX part and set variable responseText as a static all works fine. 当我从AJAX部分打开JS上方的包装并将变量responseText设置为静态时,一切正常。

Also when I will not use AJAX and just output console.log(responseText); 另外,当我不使用AJAX并仅输出console.log(responseText); I'm getting this in the console: 我在控制台中得到这个:

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

Any clue what I have missed in my case? 有什么线索让我错过了吗?

You're not sending a request to your PHP server. 您没有向您的PHP服务器发送请求。 Specify URL argument. 指定URL参数。

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

Or even better: 甚至更好:

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

OK, got it solved. 好,解决了。 JavaScript code looks like 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);
        });

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

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