Ошибка json не определено

«JSON» — неопределенная ошибка только в IE

Я делаю вызов AJAX в службу WCF, и когда я передаю свои данные, я использую JSON.преобразовать в строки()

вызов возвращается и отлично работает в FF, & Chrome, но не IE8. Я получаю сообщение об ошибке: «JSON» не определен

предложения?

p.s. Я также хочу, чтобы это работало в IE7

6 ответов



У меня была проблема с IE9. IE9 рендеринг моей страницы в режиме «причуды», решение было просто добавить <!DOCTYPE html>. Это вывело меня из режима» причуд», который, я уверен, исправил больше, чем просто эту проблему!


обновление

Регистрация JSON3 библиотека. Это работает как шарм.

изменения от JSON2

надеюсь, это поможет.


надеюсь, что это помогает. Я получил это из нескольких онлайн-источников. у них нет связей.
жаль, что я не могу привести ссылки.

var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string")
            obj = '"' + obj + '"';
        return String(obj);
    } else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof (v);
            if (t == "string")
                v = '"' + v + '"';
            else if (t == "object" && v !== null)
                v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function() {
    var r = "(?:-?b(?:0|[1-9][0-9]*)(?:.[0-9]+)?(?:[eE][+-]?[0-9]+)?b)", k = '(?:[^-x08x0a-x1f"\]|\(?:["/\bfnrt]|u[0-9A-Fa-f]{4}))';
    k = '(?:"' + k + '*")';
    var s = new RegExp(
            "(?:false|true|null|[{}[]]|" + r + "|" + k + ")", "g"), t = new RegExp(
            "\(?:([^u])|u(.{4}))", "g"), u = {
        '"' : '"',
        "/" : "/",
        "" : "",
        b : "u0008",
        f : "u000c",
        n : "n",
        r : "r",
        t : "t"
    };
    function v(h, j, e) {
        return j ? u[j] : String.fromCharCode(parseInt(e, 16));
    }
    var w = new String(""), x = Object.hasOwnProperty;
    return function(h, j) {
        h = h.match(s);
        var e, c = h[0], l = false;
        if ("{" === c)
            e = {};
        else if ("[" === c)
            e = [];
        else {
            e = [];
            l = true;
        }
        for ( var b, d = [ e ], m = 1 - l, y = h.length; m = 0;)
                            delete f[i[g]];
                }
                return j.call(n, o, f);
            };
            e = p({
                "" : e
            }, "");
        }
        return e;
    };
}();

чтобы ваша функция работала лучше в IE import json2 parser code в вашем файле, так как IE по умолчанию не поддерживает JSON.Stringify().

можно найти здесь


в IE откройте Настройки представления совместимости и удалите localhost из списка «веб-сайты, которые вы добавили в представление совместимости».
У меня получилось.


JQuery 2.x больше не совместим с IE 6-8. примечания к выпуску jQuery 2.0 beta 2

Я знаю, что главный вопрос касается более старых версий JQuery, но это вызвало ошибку для меня. Я установил JQuery 1.x, который API-совместим с JQuery 2.X, и добавил следующий код обнаружения:

<!--[if lt IE 9]>
 <script src="js/jquery-1.11.1.min.js"></script>
<![endif]-->
<!--[if gte IE 9]>
 <script src="js/jquery.min.js"></script>
<![endif]-->

We are using jQuery in our application. We have used a jQuery plugin to implement JavaScript session.

It is working properly in Firefox and most Internet Explorer 8 browsers.

But in some Internet Explorer 8 browsers it does not work. It gives the following error.

Message: 'JSON' is undefined
Line: 6
Char: 3
Code: 0


Message: '$.namesession' is null or not an object
Line: 53
Char: 2
Code: 0

`

The version of Internet Explorer in both the cases is same.

But there were some differences in Internet Explorer settings like Use SSL3.0 and Enable Smart Screen filters check boxes in the Advanced tab in the Internet options were unchecked.

When we checked it, it started working. When we unchecked them it was still working.

What is the actual problem in IE8?

If you are a Python developer, you might have encountered the error message “NameError: name ‘json’ is not defined” at some point in your coding journey. This error occurs when you try to use the json module in your code, but Python cannot find it.

how to fix nameerror name json is not defined in python

In this tutorial, we will discuss the common causes of this error and how to fix it.

Why does the NameError: name 'json' is not defined error occur?

This error occurs when you try to use the json module in your Python code, but Python cannot find the json module in its namespace. The following are some of the scenarios in which this error usually occurs.

  1. You have not imported the json module.
  2. You have imported the json module using a different name.

The json module in Python is a built-in module that allows you to encode and decode JSON (JavaScript Object Notation) data. JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. The json module provides the following two useful methods: json.dumps() to encode Python objects into a JSON formatted string, and json.loads() to decode a JSON formatted string into a Python object.

Since this module is part of the Python Standard Library, you don’t need to separately install it. You can simply import it and start using it.

Let’s now look at the above scenarios that may result in the above error in detail.

The json module is not imported

It can happen that you are trying to use the json module without even importing it. This is because Python does not recognize the json library and its functions until it is imported into the code.

For example, let’s try to use the json module without importing it and see what we get.

# note that the json module is not imported

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# print JSON string
print(person_json)

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 11
      4 person = {
      5     "name": "Kundan",
      6     "age": 26,
      7     "city": "Varanasi"
      8 }
     10 # convert dictionary to JSON string
---> 11 person_json = json.dumps(person)
     13 # print JSON string
     14 print(person_json)

NameError: name 'json' is not defined

We get a NameError stating that the name json is not defined. To use the json library, you need to import it first.

import json

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# display JSON string
person_json

Output:

'{"name": "Kundan", "age": 26, "city": "Varanasi"}'

Here, we are importing the json module first and then using it to convert a Python dictionary object into a json string. You can see that we did not get any errors here.

The json module is imported using a different name

If you import the json module using a different name, for example import json as jsn, and then try to use the name “json” to use it, you will get a NameError because the name “json” is not defined in your current namespace.

Let’s look at an example.

import json as jsn

# create a dictionary
person = {
    "name": "Kundan",
    "age": 26,
    "city": "Varanasi"
}

# convert dictionary to JSON string
person_json = json.dumps(person)

# display JSON string
person_json

Output:

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

Cell In[1], line 11
      4 person = {
      5     "name": "Kundan",
      6     "age": 26,
      7     "city": "Varanasi"
      8 }
     10 # convert dictionary to JSON string
---> 11 person_json = json.dumps(person)
     13 # display JSON string
     14 person_json

NameError: name 'json' is not defined

We get a NameError: name 'json' is not defined. This is because we have imported the josn module with the name json but we’re trying to use it using the name json.

To fix this error, you can either access json using the name that you have used in the import statement or import json without an alias. Note that generally, the convention is to import the json module without any aliases.

Conclusion

In conclusion, encountering a NameError: name 'json' is not defined error can be frustrating, but it is a common issue that can be easily fixed. By following the steps outlined in this tutorial, you should now have a better understanding of what causes this error and how to resolve it. Remember to always check your code for typos and syntax errors, and to import any necessary modules before using them in your code. With these tips in mind, you should be able to tackle any NameError errors that come your way.

You might also be interested in –

  • How to Fix – NameError: name ‘heapq’ is not defined
  • Convert Python Dictionary to JSON
  • Write a Pandas DataFrame to a JSON File
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

I am using express and Node.js. When I run the function below to get the value of an URL,
Json.stringify(url) gives me the error.

ReferenceError: Json is not defined.

app.get("/id", function (req, res, next) {
    var id = req.param("id");
    connection.query('SELECT `url` FROM dynamic_url where id =' + req.param("id"), function (error, rows, fields) {
        if (err) {
            return next(err);
        }
        var url;
        if (rows.length === 0) {
            url = 'URL not available in database'
        } else {
            url = rows[0].url;
        }
        var i = Json.stringify(url);
        res.redirect(i);
    });
});

Currently I’m writing a JavaScript file and have the following line:

var res = "JSON=" + JSON.stringify(result);

result is being set just above this line. The issue I’m having is that IE8 (IE8 only, that is) is reporting to me that JSON is undefined somehow. I’m not sure what to make of this since, as I understood it, IE8 is a browser that implemented JSON support. Does anyone have any idea what might be going on?

Mark Amery's user avatar

Mark Amery

137k78 gold badges401 silver badges450 bronze badges

asked Jan 17, 2011 at 16:23

keybored's user avatar

1

Make sure you’re actually in IE 8 mode by using the preferred method, a standards doctype…

<!DOCTYPE html>

…or the undesired method, the X-UA-Compatible meta tag/header…

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

See Defining Document Compatibility for more information.

answered Jan 17, 2011 at 16:26

Andy E's user avatar

Andy EAndy E

333k84 gold badges472 silver badges445 bronze badges

12

Using jQuery.parseJSON solved this for me, in case you are already using JQuery.

Mark Amery's user avatar

Mark Amery

137k78 gold badges401 silver badges450 bronze badges

answered Oct 2, 2013 at 8:53

Chen's user avatar

ChenChen

1951 silver badge8 bronze badges

Other things that absence of doctype or wrong doctype, or some error with html syntax, will force IE to use document modes different from what you expect.

I was using simple «» in a test document and the absence of TITLE tag as a child of HEAD tag made window.JSON become undefined.

Remember always that it’s better to test the resource against the version of browser. And, if your users can use IE’s with emulation of document modes, it’s better you have a piece of code to provide the JSON.parse and JSON.stringify when natives are undefined.

answered Sep 4, 2011 at 3:13

Arkt8's user avatar

Arkt8Arkt8

961 silver badge3 bronze badges

function parseJson(jsonString) {
    if ($.browser.msie && $.browser.version < 8) {
        return eval('(' + jsonString + ')');
    }
    else {
        return JSON.parse(jsonString);
    }
}

answered Nov 21, 2013 at 15:35

mq3w's user avatar

mq3wmq3w

734 bronze badges

1

May happen despite <!DOCTYPE html> if the page encoding is UTF-8 with BOM (byte order mark). Try saving the file as UTF-8 without BOM, using a suitable text editor.

Vikalp Patel's user avatar

Vikalp Patel

10.5k6 gold badges59 silver badges95 bronze badges

answered Feb 1, 2013 at 12:52

user126083's user avatar

put following code in your js file ;

var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

var t = typeof (obj);
if (t != "object" || obj === null) {

    // simple data type
    if (t == "string") obj = '"'+obj+'"';
    return String(obj);

}
else {

    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
        v = obj[n]; t = typeof(v);

        if (t == "string") v = '"'+v+'"';
        else if (t == "object" && v !== null) v = JSON.stringify(v);

        json.push((arr ? "" : '"' + n + '":') + String(v));
    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
if (str === "") str = '""';
eval("var p=" + str + ";");
return p;
 };

answered Mar 13, 2014 at 5:56

atom217's user avatar

atom217atom217

9711 gold badge14 silver badges24 bronze badges

1

Check jQuery version.
jQuery 2.0 drops support for IE 6, 7 and 8. Use jQuery 1.x instead, which is still officially supported.
you can use this Code.

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

read more about jquery migrate.

if not working check this article.

answered Dec 15, 2013 at 10:33

saeid mohammad hashem's user avatar

1

In my case the undefined error was because I was missing a JSON library.

You can add JSON object like this (replace the relative path with your own path):

<script>
        if (typeof window.JSON == 'undefined') {
          document.write('<script src="../scripts/json2.js"></script>'); 
        }
</script>

For json2 library:
http://cdnjs.com/libraries/json2/

There is also a json3 library:
http://cdnjs.com/libraries/json3/

Then you can refer to it in your code:

var array = [];
array[1] = "apple";
array[2] = "orange";
alert(JSON.stringify(array));

answered Jul 30, 2014 at 13:49

live-love's user avatar

live-lovelive-love

46.1k22 gold badges227 silver badges196 bronze badges

0

Currently I’m writing a JavaScript file and have the following line:

var res = "JSON=" + JSON.stringify(result);

result is being set just above this line. The issue I’m having is that IE8 (IE8 only, that is) is reporting to me that JSON is undefined somehow. I’m not sure what to make of this since, as I understood it, IE8 is a browser that implemented JSON support. Does anyone have any idea what might be going on?

Mark Amery's user avatar

Mark Amery

137k78 gold badges401 silver badges450 bronze badges

asked Jan 17, 2011 at 16:23

keybored's user avatar

1

Make sure you’re actually in IE 8 mode by using the preferred method, a standards doctype…

<!DOCTYPE html>

…or the undesired method, the X-UA-Compatible meta tag/header…

<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

See Defining Document Compatibility for more information.

answered Jan 17, 2011 at 16:26

Andy E's user avatar

Andy EAndy E

333k84 gold badges472 silver badges445 bronze badges

12

Using jQuery.parseJSON solved this for me, in case you are already using JQuery.

Mark Amery's user avatar

Mark Amery

137k78 gold badges401 silver badges450 bronze badges

answered Oct 2, 2013 at 8:53

Chen's user avatar

ChenChen

1951 silver badge8 bronze badges

Other things that absence of doctype or wrong doctype, or some error with html syntax, will force IE to use document modes different from what you expect.

I was using simple «» in a test document and the absence of TITLE tag as a child of HEAD tag made window.JSON become undefined.

Remember always that it’s better to test the resource against the version of browser. And, if your users can use IE’s with emulation of document modes, it’s better you have a piece of code to provide the JSON.parse and JSON.stringify when natives are undefined.

answered Sep 4, 2011 at 3:13

Arkt8's user avatar

Arkt8Arkt8

961 silver badge3 bronze badges

function parseJson(jsonString) {
    if ($.browser.msie && $.browser.version < 8) {
        return eval('(' + jsonString + ')');
    }
    else {
        return JSON.parse(jsonString);
    }
}

answered Nov 21, 2013 at 15:35

mq3w's user avatar

mq3wmq3w

734 bronze badges

1

May happen despite <!DOCTYPE html> if the page encoding is UTF-8 with BOM (byte order mark). Try saving the file as UTF-8 without BOM, using a suitable text editor.

Vikalp Patel's user avatar

Vikalp Patel

10.5k6 gold badges59 silver badges95 bronze badges

answered Feb 1, 2013 at 12:52

user126083's user avatar

put following code in your js file ;

var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

var t = typeof (obj);
if (t != "object" || obj === null) {

    // simple data type
    if (t == "string") obj = '"'+obj+'"';
    return String(obj);

}
else {

    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
        v = obj[n]; t = typeof(v);

        if (t == "string") v = '"'+v+'"';
        else if (t == "object" && v !== null) v = JSON.stringify(v);

        json.push((arr ? "" : '"' + n + '":') + String(v));
    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};

// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
if (str === "") str = '""';
eval("var p=" + str + ";");
return p;
 };

answered Mar 13, 2014 at 5:56

atom217's user avatar

atom217atom217

9711 gold badge14 silver badges24 bronze badges

1

Check jQuery version.
jQuery 2.0 drops support for IE 6, 7 and 8. Use jQuery 1.x instead, which is still officially supported.
you can use this Code.

<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

read more about jquery migrate.

if not working check this article.

answered Dec 15, 2013 at 10:33

saeid mohammad hashem's user avatar

1

In my case the undefined error was because I was missing a JSON library.

You can add JSON object like this (replace the relative path with your own path):

<script>
        if (typeof window.JSON == 'undefined') {
          document.write('<script src="../scripts/json2.js"></script>'); 
        }
</script>

For json2 library:
http://cdnjs.com/libraries/json2/

There is also a json3 library:
http://cdnjs.com/libraries/json3/

Then you can refer to it in your code:

var array = [];
array[1] = "apple";
array[2] = "orange";
alert(JSON.stringify(array));

answered Jul 30, 2014 at 13:49

live-love's user avatar

live-lovelive-love

46.1k22 gold badges227 silver badges196 bronze badges

0

«JSON» — неопределенная ошибка только в IE

Я делаю вызов AJAX в службу WCF, и когда я передаю свои данные, я использую JSON.преобразовать в строки()

вызов возвращается и отлично работает в FF, & Chrome, но не IE8. Я получаю сообщение об ошибке: «JSON» не определен

предложения?

p.s. Я также хочу, чтобы это работало в IE7

6 ответов



У меня была проблема с IE9. IE9 рендеринг моей страницы в режиме «причуды», решение было просто добавить <!DOCTYPE html>. Это вывело меня из режима» причуд», который, я уверен, исправил больше, чем просто эту проблему!


обновление

Регистрация JSON3 библиотека. Это работает как шарм.

изменения от JSON2

надеюсь, это поможет.


надеюсь, что это помогает. Я получил это из нескольких онлайн-источников. у них нет связей.
жаль, что я не могу привести ссылки.

var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string")
            obj = '"' + obj + '"';
        return String(obj);
    } else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n];
            t = typeof (v);
            if (t == "string")
                v = '"' + v + '"';
            else if (t == "object" && v !== null)
                v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function() {
    var r = "(?:-?b(?:0|[1-9][0-9]*)(?:.[0-9]+)?(?:[eE][+-]?[0-9]+)?b)", k = '(?:[^-x08x0a-x1f"]|(?:["/bfnrt]|u[0-9A-Fa-f]{4}))';
    k = '(?:"' + k + '*")';
    var s = new RegExp(
            "(?:false|true|null|[{}[]]|" + r + "|" + k + ")", "g"), t = new RegExp(
            "(?:([^u])|u(.{4}))", "g"), u = {
        '"' : '"',
        "/" : "/",
        "" : "",
        b : "u0008",
        f : "u000c",
        n : "n",
        r : "r",
        t : "t"
    };
    function v(h, j, e) {
        return j ? u[j] : String.fromCharCode(parseInt(e, 16));
    }
    var w = new String(""), x = Object.hasOwnProperty;
    return function(h, j) {
        h = h.match(s);
        var e, c = h[0], l = false;
        if ("{" === c)
            e = {};
        else if ("[" === c)
            e = [];
        else {
            e = [];
            l = true;
        }
        for ( var b, d = [ e ], m = 1 - l, y = h.length; m = 0;)
                            delete f[i[g]];
                }
                return j.call(n, o, f);
            };
            e = p({
                "" : e
            }, "");
        }
        return e;
    };
}();

чтобы ваша функция работала лучше в IE import json2 parser code в вашем файле, так как IE по умолчанию не поддерживает JSON.Stringify().

можно найти здесь


в IE откройте Настройки представления совместимости и удалите localhost из списка «веб-сайты, которые вы добавили в представление совместимости».
У меня получилось.


JQuery 2.x больше не совместим с IE 6-8. примечания к выпуску jQuery 2.0 beta 2

Я знаю, что главный вопрос касается более старых версий JQuery, но это вызвало ошибку для меня. Я установил JQuery 1.x, который API-совместим с JQuery 2.X, и добавил следующий код обнаружения:

<!--[if lt IE 9]>
 <script src="js/jquery-1.11.1.min.js"></script>
<![endif]-->
<!--[if gte IE 9]>
 <script src="js/jquery.min.js"></script>
<![endif]-->

Я получаю следующую ошибку с моим вызовом jquery ajax в IE9, где я использую Json.stringify().

Ошибка выполнения Microsoft JScript: «JSON» не определен

Та же функция работала у меня до вчерашнего дня и до сих пор работает на машине моих коллег и на моей машине в хроме. Но по непонятной причине перестал работать на моей машине сегодня.

Не могли бы вы помочь мне понять, что вызывает это?

Благодаря!

2 ответы

решение для меня состояло в том, чтобы отключить режим совместимости, щелкнув значок «вырванная страница» справа от адресной строки.

Кто знает, как он вообще включился!

Создан 11 фев.

ответ дан 19 апр.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

jquery
ajax
json
internet-explorer

or задайте свой вопрос.

#!/usr/bin/env python
# encoding: utf-8

import tweepy #https://github.com/tweepy/tweepy
import json as simplejson


    #write tweet objects to JSON
    file = open('tweet.json', 'wb') 
    print ("Writing tweet objects to JSON please wait...")
    for status in alltweets:
        json.dump(status._json,file,sort_keys = True,indent = 4)

    #close the file
    print ("Done")
    file.close()

if __name__ == '__main__':
    #pass in the username of the account you want to download
    get_all_tweets("@AlertZaAfrica")

The python compiler says line 54 is wrong. I already defined import json as simplejson. The above area where I defined import json is showed above.

asked Dec 6, 2016 at 18:04

rabeshi1010's user avatar

rabeshi1010rabeshi1010

1451 gold badge1 silver badge8 bronze badges

4

You should at first install simplejson to your system to be able to import it:

$ sudo pip3 install simplejson

Then in your code you are now able to import it:

import simplejson as json

From now on you will be able to access simplejson package using json.

Please note, if you’re still using python 2 — despite this is not the OPs original question — you should do a

$ sudo pip install simplejson

instead.

answered Dec 6, 2016 at 18:12

ferdy's user avatar

ferdyferdy

7,1963 gold badges34 silver badges46 bronze badges

2

Я получаю следующую ошибку в IE 9 SCRIPT5009: 'JSON' is undefined только в режиме совместимости. строка, вызывающая эту ошибку, составляет

JSON.stringify(togObj.Answers)

Ошибка не возникает, например, (режим несовместимости), Chrome или Firefox.
Любая идея, что здесь происходит?

30 нояб. 2011, в 21:23

Поделиться

Источник

7 ответов

JSON недоступен в режиме совместимости IE:

Не поддерживается в следующих режимах документа: Quirks, стандарты Internet Explorer 6, стандарты Internet Explorer 7.

Поскольку вы не должны использовать (или, что еще хуже, повторять) режимы совместимости в первую очередь, вам следует переключить IE в режим стандартов, добавив действительный doctype.

phihag
30 нояб. 2011, в 22:12

Поделиться

Я сделал LOCAL Jquery, добавленный .NEt 2.0 тестирование кода, он отлично работает без каких-либо проблем.
Но после переноса кода на сервер IIS v6, затем доступ из одного браузера IE, тогда возникает проблема «JSON» undefined.
После прочтения этой рекомендации downlode файл json2.js и добавьте ниже в исходный код.

<script  type="text/javascript" src="json2.js"></script>

ВСЕ РАБОТАЮЩИЕ Хорошо.

Хорошо Спасибо.

rajar
04 фев. 2014, в 08:17

Поделиться

Вам нужно включить json2.js

см. включение json2

для более подробной информации. Бывают случаи, когда мы имеем дело с случаями, когда клиенты используют стандарты IE7. Поэтому наш код должен был также учитывать такие случаи. К нам, являясь розничным сайтом, обращаются сотни клиентов, которые используют стандарты IE7. В том числе json2 решает эту проблему

Mohammed Rafeeq
06 сен. 2013, в 16:00

Поделиться

Если вы используете библиотеку jQuery на своей странице, вы можете использовать $.parseJSON.

iMatoria
04 сен. 2012, в 13:12

Поделиться

Ещё вопросы

  • 0Показать только выпадающий список Выбранные строки опций в таблице
  • 0Пауза видео на 3 секунды, затем возобновить воспроизведение видео
  • 0Как передать html в функцию добавления строки jquery datatables
  • 0В SQL или mySQL как найти ключ с наибольшей суммой в другом столбце, в то время как ключ отображается в двух столбцах?
  • 1У класса нет ошибки атрибута из возвращенных данных
  • 0ошибка c3861: ‘_crt_va_end’: идентификатор не найден
  • 1Блок-схема документов в Рафаэле
  • 0Jquery добавление класса в неправильную семантику
  • 1Реализация c # haversine дает другой ответ, чем googlemaps / movable-type.co.uk
  • 1Как определить, находится ли EC Point на кривой?
  • 0JQuery, как перейти к HREF DIV автоматически?
  • 0Размер long в C ++
  • 1Строка заголовка появилась снова после возвращения в моем приложении
  • 1NInject, NHIbernate и ISession в области запроса
  • 1Почему мой второй LinearLayout не отображается?
  • 1Передача коллекции предметов для поиска в LINQ
  • 1Как реализовать паттерн наблюдателя с CDI Events?
  • 0HTML, экранирующий в форме
  • 0Передача параметра Integer из Vb6 в C ++ dll
  • 1Различный список объектов в C #
  • 0Приложение, которое подключается к узлу REST API, блокируется клиентским брандмауэром
  • 0Определите изменения формы и инициируйте изменение содержимого div с помощью jQuery
  • 0Невозможно выбрать DISTINCT в запросе GROUP_CONCAT DERIVED
  • 1ItemIndex DataLIst в asp.net
  • 0Как получить значение Angular JSON
  • 1Процесс C # — отключить запрос контроля учетных записей?
  • 0Windows 8.1 — Настройка уровней масштабирования с помощью CSS
  • 0Получить данные XML на HTML-страницу с помощью http get request
  • 0Поверните div на кнопку нажмите JQuery
  • 1Добавление объектов SQL в JTable
  • 1Как получить оригинальные имена типов для элементарных типов в автоматически сгенерированных полях определенного типа в Resharper 8.1?
  • 0Получение $ _POST из флажков, которые находятся в цикле
  • 0Perl Regex для не HTML
  • 1Исключение в потоке «основной» java.lang.ArrayIndexOutOfBoundsException в java.lang.System.arraycopy (собственный метод)
  • 1Ошибки импорта проекта в Android
  • 1Связывание строк с идентификаторами TableView / TextView
  • 1Запланированная работа в многоузловой среде
  • 0Получить открытое имя файла убивает ifstream
  • 0Я хочу изменить цвет определенного текста, только если он напечатан в
  • 1Как искать слово в строке словаря в списке?
  • 0Ошибка компиляции в C ++ Возможно, проблемы с пространством имен
  • 0Установка минимальной даты в jquery datepicker
  • 1Как установить и управлять службой Windows в приложении узла js.?
  • 0PHP / MySQL категории сообщений
  • 0MySQL положить в дубликаты идентификаторов
  • 0Грунтовая установка
  • 0JQuery / JS для цикла, добавление переменной с другим конечным номером для разделения Div
  • 1Python создает регулярное выражение из списка и его вариаций
  • 1Winforms / Devexpress / Tab Control разделение концерна / Общая раскладка кода
  • 0Таблица в DIV и CSS

Сообщество Overcoder

За последние 24 часа нас посетили 8988 программистов и 810 роботов. Сейчас ищут 319 программистов …

  1. С нами с:
    27 сен 2014
    Сообщения:
    170
    Симпатии:
    14

    Здравствуйте.
    Написал корзину товаров на js , проверил в ie.
    Дебаггер в ie11 и в ie7 выдает ошибку : «JSON» не определено
    В других браузерах и других версиях ie все работает отлично.

    1. //запись массива в localStorage

    2.     localStorage.setItem(«cart», JSON.stringify(arr));

    3. //чтение массива из localStorage

    4.     arr = JSON.parse(localStorage.getItem(«cart»));

    и JSON.stringify() и JSON.parse() вызывают ошибку

    как сделать чтобы хотябы в ie11 все работало?

    Добавлено спустя 6 минут 7 секунд:
    все разобрался подключил библиотеку json-js для ie
    https://github.com/douglascrockford/JSON-js

Уважаемые коллеги!

Есть тут гуру JavaScript?

Вот такой код

<!DOCTYPE html>

<html>

<head>

<meta name=»viewport» content=»initial-scale=1.0, user-scalable=no» />

<style type=»text/css»>

  html { height: 100% }

  body { height: 100%; margin: 0px; padding: 0px }

  #map { height: 100% }

</style>

<script type=»text/javascript» src=»https://maps.google.com/maps/api/js?sensor=false»></script>;

<script src=»http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js»; type=»text/javascript»></script>

<script type=»text/javascript» src=»http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js»></script>;

<script type=»text/javascript»>

    var myMap;

    var directionsDisplay;

    var directionsService = new google.maps.DirectionsService();

    var noclick = false;

    var PointArray = [];

      function initialize() {

          directionsDisplay = new google.maps.DirectionsRenderer();

        latlng = new google.maps.LatLng(55.75, 37.62);

          var myOptions = {

          zoom: 12,

          center: latlng,

          mapTypeId: google.maps.MapTypeId.ROADMAP,

          disableDoubleClickZoom: true,

          panControl: true,

          zoomControl: true,

          mapTypeControl: true,

          scaleControl: true,

          streetViewControl: true,

          overviewMapControl: true

        };

        myMap = new google.maps.Map(document.getElementById(«map»),

           myOptions);

        
    };

<body onload=»initialize()»>

    <div id=»map» style=»width:100%; height:100%»></div>

</body>

</html>

должен просто выводить на форму пустую гугл-карту. Работает «через раз». То все нормально, то выдает ошибку «‘JSON’ is undefined.»

Никакой закономерности понять не могу — скоро мозги лопнут. За любую помощь буду благодарен…

  • Ошибка json parse error
  • Ошибка jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered перевод
  • Ошибка jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered как исправить
  • Ошибка jpeg error 42
  • Ошибка joomla cannot use object of type stdclass as array