[英]Redirect to a different url on refresh
我有帶有“ / product / create”之類的網址的“創建產品”頁面。
它具有有關該產品各種類別的多個選項卡。 提交tab-1數據(使用AJAX)時,會在服務器端創建一個產品(存儲在DB中),但URL仍然是“ / product / create”。
如果此用戶在產品創建后(例如,在tab-1上的第一次AJAX調用之后)嘗試重新加載頁面,我想將該用戶重定向到“ / product / {product_id}” 。 其余標簽可能有多個AJAX請求。
我嘗試使用刷新數據,但是在隨后的AJAX請求中丟失了數據。
session()->flash('foo','bar');
如果創建了該產品,有什么方法可以保留數據直到下一次重新加載並重定向到編輯路徑? 或其他任何可能解決我的問題的方法。
我不確定這是否是最優雅的解決方案,但是對於Chrome,您可以使用localStorage函數。 例如:
if (typeof localStorage.getItem('visited') != 'string') {
localStorage.setItem('visited', 'anything here');
} else {
localStorage.removeItem('visited');
window.location.href = 'https://www.example.com';
}
您是否嘗試過在用戶創建產品時重定向用戶?
在JavaScript中,假設產品ID在一個名為product_id
的變量中,則它將類似於:
window.location.href = "/product/"+product_id;
如果您不希望重新加載頁面,請使用PushState
var stateObj = { foo: "bar" }; //Something to the browser to know the state if user go back and forward again
history.pushState(stateObj, "NewTitle", "NewURL");
PushState導航很復雜,應該添加到整個網頁中以使其外觀更好。 推送狀態的MDN文檔
我認為,由於您使用AJAX進行提交,因此最好的方法是確保您的{product_id}與AJAX響應一起返回,以便您可以建立刷新鏈接。 在Javascript(jQuery)偽代碼中,這類似於:
// AJAX function call to createProduct
function createProduct() {
$.post('ajax-url-end-point',{payload-data}, function (ajax_response){
if(response){
//build your refresh url with response
var refreshUrl = "http://<domain>/product/"+response.productid;
localStorage.setItem('refreshUrl', refreshUrl);
window.location.href = refreshUrl
}
},'text');
}
// On reload check for the refreshUrl
$.document.ready(function() {
if(localStorage.getItem("refreshUrl")){
window.location.href = localStorage.getItem("refreshUrl");
}
});
在您的/ product / {product_id}頁面上,您可以運行JS以根據自己的特定條件擦除refreshUrl本地存儲項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.