JS:如何将选定的数据传递到下一页?

时间:2017-10-27 13:17:35

标签: javascript jquery sharepoint

我的用户有一个可以添加项目的sharepoint列表。有时他们必须创建非常相似的项目。所以我想在列表中添加一个列,其中是一个按钮或将其中一列添加到链接中。如果这样按下:

  1. 存储按钮/链接行中的项目数据。

  2. 转到新项目创建页面。

  3. 使用存储的数据自动填充所有输入文件。

  4. 这样,用户只需修改几个字段,就可以更快地完成新项目的创建。仅仅从新项目页面访问显示页面是不够的,因为我们需要至少知道项目的ID才能选择正确的项目。

    最好的方法是什么?非常感谢你的任何想法!

1 个答案:

答案 0 :(得分:1)

您可以使用可从窗口对象访问的localstorage api。

一旦你有了范围内的值,在localStorage中设置它们,你就可以在刷新后在新页面上访问该值等。

示例:

//I'm using JSON.stringify here because it will allow you to store objects, not just primitive values such as Number, String, Boolean.
window.localStorage.setItem(“key”, JSON.stringify({“Foo”:”bar”});

然后在新页面上查找

var item = window.localStorage.getItem(“key”);

//We need to parse the JSON we stringified, otherwise you'll end up with a string value.
console.log(JSON.parse(item));

这会记录:

{"Foo": "bar"}

然后您可以随意使用从我们从localStorage获取的值中检索的字段填充任何表单字段。

然后,您可以在脚本中的逻辑点清理localStorage。

window.localStorage.removeItem("key");

现在很清楚。

//This will now log undefined.
console.log(JSON.parse(window.localStorage.getItem("key"));

在代码中调用JSON.stringify和JSON.parse很容易导致它变得难以阅读。我建议您创建或使用第三方服务与其进行交互。

下面是一个简单的例子,这可以改进,绝不是一个完整的,所有的铃声和​​口哨本地存储包装。

//Create a **single** global App object, you can access the service
//hereon out with 'window.App'. 
var App = (window.App || (window.App = {}));

//Make a little service for interacting with local storage

App.Storage = {

    //Wrap the call to JSON.parse inside the service's get function
    getItem: function (key) {
         return JSON.parse(window.localStorage.getItem(key));
    },

    //Wrap the call to JSON.stringify in the service's set function
    setItem: function (key, value) {
         return window.localStorage.setItem(key, JSON.stringify(value));
    },

    //Not really neccesary as no JSON calls are used here
    //Worth adding for completeness sakes though.
    removeItem: function (key) {
        return window.localStorage.removeItem(key);
    }
};

如果你使用这样的服务,那么你的代码就会变得更好阅读。

示例:

var foo = { "Foo": "bar" };

//No JSON.stringify call :)
window.App.Storage.setItem("key", foo);

//Logs the object with no JSON.parse call directly in your business logic.
console.log(window.App.Storage.getItem("key"));

//Remove the item...
window.App.Storage.removeItem("key");

//Will now log 'undefined'
console.log(window.App.Storage.getItem("key"));

注意,在浏览器窗口中'暗示,所以你可以替换' window.App'上面有' App'。

您还可以通过在本地范围内缓存Storage服务对象来保存javascript的一些工作。

示例:

var Storage = App.Storage;

Storage.getItem();
Storage.setItem();
Storage.removeItem();