简体   繁体   English

Javascript / Jquery通过发布JSON转到页面

[英]Javascript/Jquery going to a page by posting JSON

I want to build a Json object with Jquery and then send a POST request to a server that return a web page. 我想用Jquery构建一个Json对象,然后将POST请求发送到返回网页的服务器。 I want my browser to simply print my webpage. 我希望浏览器仅打印我的网页。 I do not want to do an AJAX request. 我不想提出AJAX请求。 For the moment, I build a stupid example that send a list of string. 目前,我构建了一个愚蠢的示例,该示例发送了一个字符串列表。 I found no other way to make an invisible form with a textarea and to put my json on that field. 我发现没有其他方法可以使用textarea创建不可见的表单并将json放在该字段上。 On my server side, i retrieve this field and then parse it. 在服务器端,我检索此字段,然后对其进行解析。 Here is the side code i made for the moment : 这是我目前制作的辅助代码:

Here is my script : 这是我的脚本:

$(function () {
    var text_input = $("#text_input");
    var json_pre = $("#json");
    var object = {"list":[]};
    var button = $("#button");
    var textarea_data = $("#textarea_data");

    button.click(function(e) {

        object.list.push(text_input.val());

        text_input.val("");

        json_pre.text(JSON.stringify(object, null, 4));

        textarea_data.val(JSON.stringify(object));
    });


    text_input.keypress(function (e) {
        if (e.keyCode === 13) {
            button.trigger("click");
        }
    });

    $("#send").click(function (e) {
        $("#form").submit();
    });

});

And here is my html : 这是我的html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Listify</title>


</script>
</head>
<body>
    <input type="text" id="text_input" />
    <button type="button" id="button">Add</button>
    <h2>Json envoyé à la JSP</h2>
    <p>
    <pre id="json"></pre>
    </p>

    <form id="form" action="./listify" method="post" style="display:none;">
        <textarea name="data" id="textarea_data">
        </textarea>
    </form>

    <button type="button" id="send">Send</button>
    <script
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="listify_script.js"></script>
</body>
</html>

But i am not satisfy of my answer because the request Content-Type is not Json and it don't seems elegant to me : 但是我不满意我的回答,因为请求Content-Type不是Json,并且对我来说似乎并不优雅:

POST /wxj/listify HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 69
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/wxj/listify
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
data=%7B%22list%22%3A%5B%22Luc%22%2C%22Anotin%22%2C%22Pierre%22%5D%7D

If I transform my code to an Ajax code this way : 如果我以这种方式将代码转换为Ajax代码:

$(function () {
    var text_input = $("#text_input");
    var json_pre = $("#json");
    var object = {"list":[]};
    var button = $("#button");
    var textarea_data = $("#textarea_data");

    button.click(function(e) {

        //ajout du texte dans mon objet
        object.list.push(text_input.val());

        //effacer le texte de bar de text
        text_input.val("");


        //pour la pedagogie
        json_pre.text(JSON.stringify(object, null, 4));


        //ajout du json objet dans textarea
        textarea_data.val(JSON.stringify(object));
    });


    text_input.keypress(function (e) {
        if (e.keyCode === 13) {
            button.trigger("click");
        }
    });

    $("#send").click(function (e) {
        //$("#form").submit();

        $.ajax("./listify", {
            type:"POST",
            contentType:"application/json",
            data : JSON.stringify(object)
        });
    });

});

Now you can see that the contentType is application/json and the Json is directly into the body and not url encoded : 现在您可以看到contentType是application / json,而Json直接进入了主体,并且没有url编码:

POST /wxj/listify HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 31
Accept: */*
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8080/wxj/listify
Accept-Encoding: gzip,deflate,sdch
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
{"list":["test","json","ajax"]}

Unfortunatly using the ajax jquery method does not make my browser "moving to the result". 不幸的是,使用ajax jquery方法不会使我的浏览器“移至结果”。

I found a workaround using document.open : 我发现使用document.open的解决方法:

$("#send").click(function (e) {
    //$("#form").submit();

    $.ajax("./listify", {
        type:"POST",
        contentType:"application/json",
        data : JSON.stringify(object),
        success : function (data) {
            window.history.pushState( {"foo": "stats"}, "listify", "../listify");
            var newDoc = document.open("text/html", "replace");
            newDoc.write(data);
            newDoc.close();
        }
    });
});

Unfortunatly the call to window.history.pushState does correctly save the page before newDoc, at least on Chrome. 不幸的是,至少在Chrome上,对window.history.pushState的调用确实将页面正确保存在newDoc之前。 Pressing the back button does not go to the state before the response. 按下返回按钮不会进入响应之前的状态。

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

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