简体   繁体   English

使用javascript / jquery检索发布数据

[英]Retrive post data back using javascript/jquery

I want to pass the object to the new page by using only client side script(javascript), and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it. 我想仅使用客户端脚本(javascript)将对象传递到新页面,并且我想在加载新页面时读回数据,但是我找不到任何教程或方法来获取它。

function postToURL(path, parameters) {
    var form = $('<form></form>');

    form.attr("method", "post");
    form.attr("action", path);

    $.each(parameters, function(key, value) {
        var field = $('<input></input>');

        field.attr("type", "hidden");
        field.attr("name", key);
        field.attr("value", value);

        form.append(field);
    });

    // The form needs to be a part of the document in
    // order for us to be able to submit it.
    $(document.body).append(form);
    form.submit();
}

The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot. 浏览器未将发送到服务器以检索当前页面的POST消息公开给该页面中的JavaScript,因此您无法这样做。

Pass the data via some other technique (such as through the URL, or localstorage). 通过其他某种技术(例如,通过URL或localstorage)传递数据。

Yeah, POST data is only handled and seen by the server side (ex. PHP). 是的,POST数据只能由服务器端(例如PHP)处理和查看。 Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript). Javascript位于客户端,因此除非POST数据首先传递到服务器端,然后服务器端又将其交给客户端(例如Javascript),否则它将永远无法看到该数据。

Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript. 考虑在上面的代码中使用GET作为您的方法,以便您可以在实际URL中传递参数,以使其可被浏览器/客户端/ Javascript访问。

parameters can be parsed from a JSON-encoded string. 可以从JSON编码的字符串中解析parameters If you build your parameters programmically (in the previous step) like: 如果您通过编程方式(在上一步中)构建参数,例如:

parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';

You can create a flat JSON String representing your structured data by: 您可以通过以下方式创建表示您的结构化数据的平面JSON字符串:

parametersString = JSON.stringify(parameters);

and end up with something like this: 最后是这样的:

"{'USA': 'Washington DC', 'UK': 'London'}"

You can store this string in a cookie , or in a query string or fragment part of the URL. 您可以将此字符串存储在Cookie或URL的查询字符串片段部分中。

Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like: 您的下一页可以在下一页上读回此值,并通过解码JSON字符串来重新创建结构化参数,例如:

parameters = JSON.parse(parametersString);

and you're getting the original data back, on which you can run JQuery's each . 您将获得原始数据,可以在其上运行JQuery的each

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

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