Set content type based on browser - javascript

I am using asp.net mvc 3 and returning json to the user. I'm doing that with:
return Json(results, JsonRequestBehavior.AllowGet)
results is just a simple viewmodel c# class I created. That works fine in FF and chrome, but then IE 9 asks to open or save the results. Everywhere I look, people say the "fix" is to do something like:
return Json(results, "text/html", JsonRequestBehavior.AllowGet)
This does work for me in IE, but it doesn't work in chrome and/or firefox. It does for some versions, but not all. I was wondering if it's possible to return text/html if the browser is IE, otherwise return the normal JSON. Or is there a better solution? Thanks in advance!

I am assuming that you are doing an AJAX call, if so the solution you have is the correct way to make ALL browsers treat the returned values as HTML, which is a much better solution than dealing with each browser in a different way.
However, in order to be able to work with the returned values, you will need to parse the returned html into JSON.
In the success callback of the AJAX call, simply add the following:
var jsonResponse = $.parseJSON(response);

Related

IE7 JSON object being appended to basepage url

I'm having strange IE7 behavior at the moment. We reach out to an external service that returns a formatted JSON object back to us. Any other version of IE can handle this object. However in IE7, it simply appends the JSON string to the end of the basepage url. so we end up with something like this...
http://localhost:1111/X?Param=223"#13988652796891&{"TestCodes":{"TestCode":.....
The page then takes it upon itself to refresh, and breaks because the url isn't correct. Has anyone seen anything like this before, and if so was there something they were using that caused this to happen? I can give a few more details, I have other issues debugging because I do not have an actual instance of IE7 on this machine. (I've been using IETester, but I can't actually step through code this way)
Thanks in advance!

Parsing JSON in javascript for multiple browsers

I'm trying two different approaches. One works in only Firefox, the other works in Safari, but neither work in both. The one that works in Firefox is:
var json = JSON.parse(data);
var results = json.query.results.quote;
The one that works in Safari
var results = data.query.results.quote;
Where data is the JSON that is being returned from a server. Is one of these the proper ways to parse JSON, and what's the best way for browser compatibility
EDIT:
When I debug in Safari using JSON.parse I get the error: Unexpected identifier "object"
If you are using jQuery to get this JSON data, you don't need to worry about parsing it. jQuery can (and sometimes will) do it for you.
Your problem is (probably) that it is already being parsed for you. If you server returns the Content-type: application/json header, jQuery will parse it for you. If it returns a different header, like text/html, then it won't be parsed as JSON. It's never good to be unsure of what a variable contains.
To tell jQuery to always parse it as JSON, use dataType: 'json'. This makes sure that the data in your callback is always an object.
$.ajax({
url: 'file.php',
dataType: 'json',
success: function(data){
var results = data.query.results.quote;
}
});
You can use the official implementation of JSON by Douglas Crockford. It's available here. Major libraries make sure to add JSON functionality. It is also very easy to check if a native implementation of JSON is available within the existing browser.
The JSON library already does that. It checks to see if the browser already has JSON.parse and JSON.stringify implemented. If it does, it won't override anything. If it doesn't it will give you the functionality you need.

In what situation would document.open() return null?

I'm trying to understand an intermittent script error that I am seeing in a JavaScript intensive thin-client application running under Internet Explorer 6 and Windows XP. The root cause of the problem is that the following function call returns a null value (however it does succeed without an error):
var doc = targetWindow.document.open("text/html","_replace");
Where targetWindow is a window object.
Neither targetWindow nor targetWindow.document is null and so I'm struggling to understand why this call would return null. My interpretation of the documentation is that this method shouldn't ever return null.
This code has been unchanged and working perfectly for many years - until I understand why this is happening I'm not sure either how I might handle this, or what might have changed to cause this to start happening.
What might cause this function call to return null?
According to the documentation you should be passing "replace", not "_replace". Try this instead:
var doc = targetWindow.document.open("text/html", "replace");
Since you say your code has worked for years, then it is likely that something has changed and the above suggestion may not be the issue. However, it is still worth a try.
Have you changed any js files / libraries you are using in your application lately? Also, are you using any browser plugins within the page? It is possible that a newer version of either of these could be somehow affecting your call to "document.open".
document.open() does not have any parameters by W3C standard. Check out this link: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-72161170
I recommend you to use W3C documentation instead of Microsoft's one because with W3C you are sure it works on all modern browsers, while Microsoft is well known for adding extensions that, of course, works only in their own products. It's called EEE (Embrace, extend and extinguish).
Simply use document.open() without arguments. There are ways to manipulate user history, but that's called bad programming practice. History is user's private data and web application should not try to manipulate it.

How to access JSON from an iframe originating from same domain?

In my webpage a hidden iframe is loaded with some JSON in it. This JSON is refreshed by some actions on the page. How do I access this JSON in iframe from my web page? for some unknown arcane unexplainable reason I am forced to use jQuery 1.3.2. so no $.parseJSON()
I think you can use:
var json = $.parseJSON($("#hiddeniframe").contents().text());
Something along those lines will work at least.
All modern browsers include a JSON parsing library:
var data = JSON.parse($("#hiddeniframe").contents().text());
If you need to support older browsers there are several libraries to choose from that will provide the same interface. The better ones will check to see if the browser is providing a native implementation and not override it, since it's bound to be faster.
See also JSON.stringify()
The code #Paulpro posted:
var json = $.parseJSON($("#hiddeniframe").contents().text());
doesn't work for me.
I changed the code to:
var json = $.parseJSON($("#hiddeniframe").contents().find("*").first().text());
And now it works.

Getting URL of executing JavaScript file (IE6-7 problem mostly)

Hey all, I've been trying to throw together a generic function that retrieves the absolute URL of an executing JavaScript file on a web page:
http://gist.github.com/433486
Basically you get to call something like this:
getScriptName(function(url) {
console.log(url);
// http://www.example.com/myExternalJsFile.js
});
inside an external JavaScript file on a page and can then do something with it (like find the <script> tag that loaded it for example).
It works great in almost all the browsers I've tested (Firefox, Chrome, Safari, Opera v10 at least, and IE 8).
It seems to fail, however, in IE 6 and 7. The callback function gets executed, but the retrieved name is the URL to the main HTML page, not the JavaScript file. Continuing with the example, getScriptName invokes the callback with the parameter: http://www.example.com/index.html
So all I'm really asking is if there's some other way of getting the URL of the current JavaScript file (which could be IE 6 and 7 specific hackery)? Thanks in advance!
EDIT: Also, this won't work in every case, so please don't recommend it:
var scripts = document.getElementsByTagName("script");
return scripts[scripts.length-1].src;
I'd like it to work in the case of dynamically created script tags (possibly not placed last in the page), aka lazy-loading.
A lot of this depends on what you have access to. If, as it appears, you are trying to do this entirely within the JS code, I do not believe that you are able to do it, for some of the reasons shown above. You could get 90% of the way maybe, but not be definitive.
If you are working in a dotnet environment ( which is the only one I know ), I would suggest the use of a module that would intercept all JS requests and add into them the request location, or something of that nature.
I think you need to address this from the server side, not the client side. I do not think you will have a definitive answer form the client side. I think you will also struggle to get an answer from the server side, but you might be more successfull.
Sorry, I suspect you might struggle with this. IE earlier than version 8 typically gives error messages from javascript errors of the form:
line: 342
char: 3
error: expected identifier, string or number
code: 0
url: http://example.com/path/to/resource
where the url is the window.location.href, rather than the URL of the external Javascript resource that contains the problem. I suggest that IE gives the unhelpful URL value since the script URL isn't available to IE at that point, and neither is it available to any Javascript you might write to try to display it.
I would love to be able to link to IE8 release notes which say this bug / feature has been fixed, hence the reason I created this as community wiki. My MSDN foo is pretty weak!

Categories

Resources