recently,i met with a problem that.
there is one page:pageA,there are some in it. the url of which will lead u to another page:pageB .
however ,i want to jump with some params or data while not changing the url of the pageB. is there any good solutions? i'm using react,but not a single page project.
There are couple of ways of doing it like using cookies, spring webflow(if its spring application ) or using Local/Session Storage
Web Storage is a feasible and an easy approach
In page A you can store the value in a local storage using key & value
if (typeof(Storage) !== "undefined") {
localStorage.setItem("anyunique Key Name ", "value which you want to store");
} else {
// Sorry! No Web Storage support..
}
In page B use same LocalStorage's getItem() method to retrieve the value
document.getElementById("someDOM").innerHTML = localStorage.getItem("key");
Related
I use UIWebView in the iOS project.
In js code in this webview I use local storage (reading data from local storage by key and writing data to local storage by key).
var items = JSON.parse(localStorage.getItem('key')) || []; //reading
localStorage.setItem('key', newJson); // writing
Now I use only one key for using local storage.
It works fine.
But local storage in common for all UIWebViews in the project (Am I right or not?). And when I use two or more UIWebView in the project (js code is similar for all webviews), that I need use more than one key for using local storage (one key for every UIWebView) in order to every webview use own storage.
How I can define which UIWebView uses local storage now in order to use key for this UIWebView?
How I can get UIWebViews id in java script?
You can save an object in localStorage().
In this way you can save data for more that one UIWebView in client memory and retrieve it easily by key.
An example:
// create an object with some properties (as value use data from UIWebView)
var uIWebViews = { 'uIWebView1': 1, 'uIWebView2': 2, 'uIWebView3': 3 };
// save your object into local storage
localStorage.setItem('uIWebViews', JSON.stringify(uIWebViews));
// retrieve the object from storage, remember to parse it
var retrievedObject = JSON.parse(localStorage.getItem('uIWebViews'));
// get the object
console.log('retrievedObject: ', uIWebViews);
// get a property, equivalent to get a key
console.log('key uIWebView2 has value: ', uIWebViews.uIWebView2);
Live example, please open console to see the result: https://jsfiddle.net/hsf8gf8d/
To let the JS code know what webview it runs in I would call its stringByEvaluatingJavaScriptFromString: method with a predefined JS method that sets a variable in your page. So your JS code could have something like
function setWebViewID(webViewID) {
// save the identifier somewhere and perhaps call other functions
}
Then in the webView, once the page is loaded and all, you call
[myWebView stringByEvaluatingJavaScriptFromString:#"setWebViewID(\"myID\")"]
The trick is usually ensuring that the content is done with any other stuff it does in JS right after loading. If you need something like that I'd recommend using WKWebView, WKUserContentController and to look into addScriptMessageHandler:name:. With that you can properly set up listening for events in JS from the webview.
I have a function that request a data for the user one time. I need reload the page after save these data in a cookie and server read these cookie, but i dont know if these cookie are defined or not. ¿How i reload only one time if i dont have a counter and dont like use parameter? the referrer dont change with reload.
I now have this methot, but i like change for remove parameters:
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null
}
if (getURLParameter('reload') != 'true') {
//here have function for load cookie
window.location = window.location.href + '?reload=true';
}
HTTP is a stateless protocol, which mean there is not way - within the protocol - to know the state of a request. For instance : is it the first time it's launched or the second time ?
Usual workarounds are adding a parameter to the request, as you suggests or using a cookie on the browser's side. This is how sessions are implemented in platforms like Java EE or PHP.
Why don't you test for another cookie like 'never been reloaded', if it does not exists : create this cookie and reload the page.
The tricky part is when should you delete the cookie, ie : when does your business logic wants you to reload the page again ? That's up to you to decide.
According to the W3 Web Storage specs, values in localStorage are of type string.
Thus, an entry can't be granularly updated like a subproperty of a JS object and it's only possible to replace the entire key:
Updating/editing localStorage - JSONObject
Assume I want to "secure" user input frequently on the client side in the localStorage, and also update it on model changes on the server (only transmitting changes from server to client). How often can I JSON.stringify() my local data (=ViewModel state) and save it to the localStorage without causing trouble for the user? Is serializing and saving (not transmitting!) e.g. 30KB of data every 5 seconds to the localStorage going to cause lags?
Bonus question: Does any major browser vendor plan on storing JS objects directly in localStorage?
This may not be entirely true; there is a method for updating a single key to an object housed in local storage, and the code is below.
var updateLocalStorageKey = function(obj, key, val) {
var localObj = JSON.parse(localStorage[obj] )
localObj[key] = val;
//reset storage
localStorage[obj] = JSON.stringify(localObj)
}
The working jsbin is here: http://jsbin.com/jesapifa/4/edit?html,js,output
Hope this solves your problem!
I have a mobile application that opens an in-app browser that uses the URL to pass information to my server , like the deviceID.
For example the browser will open the web-page (jquery Mobile) : www.myserver.com/doWork.html#deviceID
On the server part using JavaScript inside the doWork.html file, I get the deviceID like this:
var userId = window.location.hash.substring(1);
Is it ok that i pass information using the hash # ? In jquery mobile the hash # is used to change between pages when someone uses the Multi-Page template structure . So i am afraid that maybe i should use something else , like a question mark (?) ?
Or its perfectly fine ?
NO. Stop using # for your data transfers. Let jQM do its thing. Don't disturb it. Use Query strings( adding ? in url). My advice is to stop using query strings (? tags) and # tags to send data to the next page. Handle it using localStorage. Its more secure compared to Query strings because the user wont see the URL change, so your sensitive data is hidden, at least to a little extent. localStorage is HTML5's API which is like a temporary storage set aside per domain. This data will persist until data is cleared in cache. Assuming you have an anchor tag which goes to dowork.html,
Go to Do work
Add an attribute for device ID in the tag itself, like this :
Go to Do work
You'd be doing this dynamically you might also use it the same way. You get the gist right?
A click event for this would look like this :
$(document).on("click", "a", function(e) //use a class or ID for this instead of just "a"
//prevent default
e.preventDefault();
//get device id from tag attribute
var deviceId = $(this).data("deviceid");
//set it in localStorage
localStorage["dId"] = deviceId;
//redirect
$.mobile.changePage(this.href);
});
Then, in the other page's pageinit (or any event), get the device id from storage and send the ajax call to the server.
//assuming #dowork is the id of a div with data-role="page"
$(document).on("pageinit", "#dowork", function() {
//get from storage
var deviceId = localStorage["dId"];
//make ajax call or server call with deviceId here
});
But, if you still want to use URL for this, look at this question. I've given a decent enough answer over there.
To pass variables to the server you should avoid using the # symbol because regardless of the framework you are using this symbol is used for other purposes, to pass info to the server in a GET request you should use the ? symbol, something like this should do it: www.myserver.com/doWork.html?deviceID=1233455
I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.