Модератор: april22
Ошибка web-морды
Добрый день. В один прекрасный момент, при нажатии кнопки Apply config, выскочило
«Error: Did not receive valid response from server
XHR response code: 200 XHR responseText: undefined jQuery status: parsererror»
После этого ничего по человечески настроить через web не получается. Но через конфиги всё работает как нужно.
Посоветуйте, пожалуйста, что можно сделать.
- Topotyn
- Сообщений: 16
- Зарегистрирован: 07 июл 2015, 15:22
Re: Ошибка web-морды
ded » 27 ноя 2015, 16:42
- ded
- Сообщений: 15466
- Зарегистрирован: 26 авг 2010, 19:00
Re: Ошибка web-морды
Topotyn » 27 ноя 2015, 16:52
Скорее плохо с английским, чем с поисковиком. Но намёк понял.
- Topotyn
- Сообщений: 16
- Зарегистрирован: 07 июл 2015, 15:22
Re: Ошибка web-морды
Topotyn » 27 ноя 2015, 16:58
Вот так и получается, Вы меня пристыдили, и я всё сделал сам. Спасибо!
- Topotyn
- Сообщений: 16
- Зарегистрирован: 07 июл 2015, 15:22
Re: Ошибка web-морды
ded » 27 ноя 2015, 17:09
Всё время к этому подталкиваю.
Ещё бы Вам опубликовать тут решение этой проблемы…
Если плохо с английским — надо так:
http://bfy.tw/3082
Последний раз редактировалось ded 27 ноя 2015, 17:14, всего редактировалось 1 раз.
- ded
- Сообщений: 15466
- Зарегистрирован: 26 авг 2010, 19:00
Re: Ошибка web-морды
Topotyn » 27 ноя 2015, 17:11
- Topotyn
- Сообщений: 16
- Зарегистрирован: 07 июл 2015, 15:22
Re: Ошибка web-морды
awsswa » 21 май 2019, 21:47
Снова нарвался на эту ошибку — довольно редкая
Помогла внимательность
Что то глюкнуло и в manager.conf записалось
два admin с разными правами
и второй admin был порезанными правами
удаление лишнего [admin] решило проблему
платный суппорт по мере возможностей
- awsswa
- Сообщений: 2390
- Зарегистрирован: 09 июн 2012, 10:52
- Откуда: Россия, Пермь skype: yarick_perm
Вернуться в Вопросы новичков
Кто сейчас на форуме
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 12
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
Содержание
- How to make HTTP requests using XMLHttpRequest (XHR)
- Basic XHR Request
- xhr.open() Method
- xhr.send() Method
- XHR Events
- Request Timeout
- Response Type
- Request States ( xhr.readyState )
- Aborting Request
- Synchronous Requests
- HTTP Headers
- XHR POST Request
- XHR POST Request with with application/x-www-form-urlencoded
- XHR POST Request with JSON Data
- Cross-Origin Requests & Cookies
- XHR vs. jQuery
- XHR vs. Fetch API
- Handling Ajax errors with jQuery.
- JQuery 3.0: The error, success and complete callbacks are deprecated.
- One thought on “ Handling Ajax errors with jQuery. ”
- jQuery ajax readystate 0 состояние responsetext 0 ошибка statustext
- 5 ответов
- XMLHttpRequest
- The basics
- Response Type
- Ready states
- Aborting request
- Synchronous requests
- HTTP-headers
- POST, FormData
- Upload progress
- Cross-origin requests
- Summary
How to make HTTP requests using XMLHttpRequest (XHR)
XMLHttpRequest is a built-in browser object in all modern browsers that can be used to make HTTP requests in JavaScript to exchange data between the web browser and the server.
Despite the word «XML» in its name, XMLHttpRequest can be used to retrieve any kind of data and not just XML. We can use it to upload/download files, submit form data, track progress, and much more.
Basic XHR Request
To send an HTTP request using XHR, create an XMLHttpRequest object, open a connection to the URL, and send the request. Once the request completes, the object will contain information such as the response body and the HTTP status code.
Let’s use JSONPlaceholder to test REST API to send a GET request using XHR:
The xhr.onload event only works in modern browsers (IE10+, Firefox, Chrome, Safari). If you want to support old browsers, use the xhr.onreadystatechange event instead.
xhr.open() Method
In the example above, we passed the HTTP method and a URL to the request to the open() method. This method is normally called right after new XMLHttpRequest() . We can use this method to specify the main parameters of the request:
Here is the syntax of this method:
- method — HTTP request method. It can be GET , POST , DELETE , PUT , etc.
- URL — The URL to request, a string or a URL object
- asnyc — Specify whether the request should be made asynchronously or not. The default value is true
- username & password — Credentials for basic HTTP authentication
The open() method does not open the connection to the URL. It only configures the HTTP request.
xhr.send() Method
The send() method opens the network connection and sends the request to the server. It takes an optional body parameter that contains the request body. For request methods like GET you do not need to pass the body parameter.
XHR Events
The three most widely used XHR events are the following:
- load — This event is invoked when the result is ready. It is equivalent to the xhr.onreadystatechange event with xhr.readyState == 4 .
- error — This event is fired when the request is failed due to a network down or invalid URL.
- progress — This event is triggered periodically during the response download. It can be used to report progress for large network requests.
Request Timeout
You can easily configure the request timeout by specifying the time in milliseconds:
xhr.responseURL property returns the final URL of an XMLHttpRequest instance after following all redirects. This is the only way to retrieve the Location header.
Response Type
We can use the xhr.responseType property to set the expected response format:
- Empty (default) or text — plain text
- json — parsed JSON
- blob — binary data Blob
- document — XML document
- arraybuffer — ArrayBuffer for binary data
Let’s call a RESTful API to get the response as JSON:
Request States ( xhr.readyState )
The XMLHttpRequest object changes state as the request progresses. We can access the current state using the xhr.readyState property.
The states are:
- UNSENT (0) — The initial state
- OPENED (1) — The request begins
- HEADERS_RECEIVED (2) — The HTTP headers received
- LOADING (3) — Response is loading
- DONE (4) — The request is completed
We can track the request state by using the onreadystatechange event:
Aborting Request
We can easily abort an XHR request anytime by calling the abort() method on the xhr object:
Synchronous Requests
By default, XHR makes an asynchronous request which is good for performance. But if you want to make an explicit synchronous request, just pass false as 3rd argument to the open() method. It will pause the JavaScript execution at send() and resume when the response is available:
Be careful! Chrome display the following warning for synchronous XHR request: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects on the end user’s experience.
XMLHttpRequest allows us to set request headers and read response headers. We can set the request Content-Type & Accept headers by calling setRequestHeader() method on the xhr object:
Similarly, if you want to read the response headers (except Set-Cookie ), call get response header() on the xhr object:
Want to get response headers at once? Use getAllResponseHeaders() instead:
XHR POST Request
There are two ways to make a POST HTTP request using XMLHttpRequest : URL encoded form-data and FormData API.
XHR POST Request with with application/x-www-form-urlencoded
The following example demonstrates how you can make a POST request with URL-encoded form data:
XHR POST Request with JSON Data
To make an XHR POST request with JSON data, you must the JSON data into a string using JSON.stringify() and set the content-type header to application/json :
Cross-Origin Requests & Cookies
XMLHttpRequest can send cross-origin requests, but it is subjected to special security measures. To request a resource from a different server, the server must explicitly support this using CORS (Cross-Origin Resource Sharing).
Just like Fetch API, XHR does not send cookies and HTTP authorization to another origin. To send cookies, you can use the withCredentials property of the xhr object:
XHR vs. jQuery
jQuery wrapper methods like $.ajax() use XHR under the hood to provide a higher level of abstraction. Using jQuery, we can translate the above code into just a few lines:
XHR vs. Fetch API
The Fetch API is a promise-based modern alternative to XHR. It is clean, easier to understand, and massively used in PWA Service Workers.
The XHR example above can be converted to a much simpler fetch() -based code that even automatically parses the returned JSON:
Read JavaScript Fetch API guide to understand how you can use Fetch API to request network resources with just a few lines of code.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
Источник
Handling Ajax errors with jQuery.
This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.
Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:
If you look at the code above, you will notice that I have two functions:
- success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
- error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.
The Ajax error function has three parameters:
In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:
- status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
- statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.
Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.
JQuery 3.0: The error, success and complete callbacks are deprecated.
Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.
An example of done and fail being used:
Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.
Hopefully, you found this tutorial to be useful.
One thought on “ Handling Ajax errors with jQuery. ”
thanks its helpful 🙂 many of us not aware of error block in ajax
Источник
jQuery ajax readystate 0 состояние responsetext 0 ошибка statustext
Я получаю следующую ошибку: jquery ajax readystate 0 responsetext status 0 statustext error когда он: url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm) , однако он работает нормально, когда я даю его url(localhost:»»/embparse_page) на моем localhost.
Я попытался использовать заголовки, которые я нашел в поиске Google, и я использовал beforeSend:»» тоже, но это все еще не работает.
Я думаю, что главная проблема: XMLHttpRequest cannot load http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm. Origin «local server» is not allowed by Access-Control-Allow-Origin. но я этого не понимаю.
может кто-нибудь объяснить мне проблему, так как я совершенно новичок в этом.
5 ответов
Я получал эту ошибку, и в моем случае это не было связано с той же политикой происхождения. Я получил некоторую помощь от этой ссылке
мой случай был, у меня была кнопка ссылки, и я не использовал e.PreventDefault ()
ASPX
в JavaScript
та же политика происхождения. браузер не позволяет, когда вы находитесь на
для подключения к:
это так site1 не может украсть контент из site2 и притвориться, что это содержимое site1. Способы обойти это JSONP (Google maps используют, что я думаю) и имеющие site2 предоставить заголовки cors, но cors не поддерживаются в jQuery 1.* (может быть, не в 2.* либо), потому что IE имеет некоторые проблемы с его реализацией. В обеих ситуациях вам нужно site2 сотрудничать с вашим сайт, чтобы ваш сайт мог отображать его содержимое.
Если вы используете только это самостоятельно, то вы можете использовать Firefox и установить плагин forcecors. Для активации вы можете выбрать view => toolbars => add on bar и нажать на текст «cors» в правой нижней части экрана.
Я получал эту ошибку от моего вызова Ajax, и то, что исправило ее для меня, просто вставило «return false».
у меня была такая же проблема с Nginx (на стороне сервера ) и AngularJs (на стороне пользователя )
как сказал другой разработчик свою проблему Cors, здесь я просто хочу сказать, как я решаю свою проблему, может быть, кто-то использует этот подход 😉
сначала я добавил ниже строки в мои конфигурационные файлы Nginx (в linux — > /etc/nginx/sites-available / your domain) :
и с angularJs я отправляю свой запрос следующим образом:
я тестировал чтение на json/xml data и получил ошибку. значения содержания: Status[0] & readyState[0] и StatusText[error]; это успешно работает в Internet explorer, но не в Chrome, потому что домен должен быть таким же
это то, что исправлено
перейти к C:WINDOWSsystem32driversetchosts
поместите имя против вашего приложения localhost:
Источник
XMLHttpRequest
XMLHttpRequest is a built-in browser object that allows to make HTTP requests in JavaScript.
Despite having the word “XML” in its name, it can operate on any data, not only in XML format. We can upload/download files, track progress and much more.
Right now, there’s another, more modern method fetch , that somewhat deprecates XMLHttpRequest .
In modern web-development XMLHttpRequest is used for three reasons:
- Historical reasons: we need to support existing scripts with XMLHttpRequest .
- We need to support old browsers, and don’t want polyfills (e.g. to keep scripts tiny).
- We need something that fetch can’t do yet, e.g. to track upload progress.
Does that sound familiar? If yes, then all right, go on with XMLHttpRequest . Otherwise, please head on to Fetch.
The basics
XMLHttpRequest has two modes of operation: synchronous and asynchronous.
Let’s see the asynchronous first, as it’s used in the majority of cases.
To do the request, we need 3 steps:
The constructor has no arguments.
Initialize it, usually right after new XMLHttpRequest :
This method specifies the main parameters of the request:
- method – HTTP-method. Usually «GET» or «POST» .
- URL – the URL to request, a string, can be URL object.
- async – if explicitly set to false , then the request is synchronous, we’ll cover that a bit later.
- user , password – login and password for basic HTTP auth (if required).
Please note that open call, contrary to its name, does not open the connection. It only configures the request, but the network activity only starts with the call of send .
This method opens the connection and sends the request to server. The optional body parameter contains the request body.
Some request methods like GET do not have a body. And some of them like POST use body to send the data to the server. We’ll see examples of that later.
Listen to xhr events for response.
These three events are the most widely used:
- load – when the request is complete (even if HTTP status is like 400 or 500), and the response is fully downloaded.
- error – when the request couldn’t be made, e.g. network down or invalid URL.
- progress – triggers periodically while the response is being downloaded, reports how much has been downloaded.
Here’s a full example. The code below loads the URL at /article/xmlhttprequest/example/load from the server and prints the progress:
Once the server has responded, we can receive the result in the following xhr properties:
status HTTP status code (a number): 200 , 404 , 403 and so on, can be 0 in case of a non-HTTP failure. statusText HTTP status message (a string): usually OK for 200 , Not Found for 404 , Forbidden for 403 and so on. response (old scripts may use responseText ) The server response body.
We can also specify a timeout using the corresponding property:
If the request does not succeed within the given time, it gets canceled and timeout event triggers.
To add parameters to URL, like ?name=value , and ensure the proper encoding, we can use URL object:
Response Type
We can use xhr.responseType property to set the response format:
- «» (default) – get as string,
- «text» – get as string,
- «arraybuffer» – get as ArrayBuffer (for binary data, see chapter ArrayBuffer, binary arrays),
- «blob» – get as Blob (for binary data, see chapter Blob),
- «document» – get as XML document (can use XPath and other XML methods) or HTML document (based on the MIME type of the received data),
- «json» – get as JSON (parsed automatically).
For example, let’s get the response as JSON:
In the old scripts you may also find xhr.responseText and even xhr.responseXML properties.
They exist for historical reasons, to get either a string or XML document. Nowadays, we should set the format in xhr.responseType and get xhr.response as demonstrated above.
Ready states
XMLHttpRequest changes between states as it progresses. The current state is accessible as xhr.readyState .
An XMLHttpRequest object travels them in the order 0 → 1 → 2 → 3 → … → 3 → 4 . State 3 repeats every time a data packet is received over the network.
We can track them using readystatechange event:
You can find readystatechange listeners in really old code, it’s there for historical reasons, as there was a time when there were no load and other events. Nowadays, load/error/progress handlers deprecate it.
Aborting request
We can terminate the request at any time. The call to xhr.abort() does that:
That triggers abort event, and xhr.status becomes 0 .
Synchronous requests
If in the open method the third parameter async is set to false , the request is made synchronously.
In other words, JavaScript execution pauses at send() and resumes when the response is received. Somewhat like alert or prompt commands.
Here’s the rewritten example, the 3rd parameter of open is false :
It might look good, but synchronous calls are used rarely, because they block in-page JavaScript till the loading is complete. In some browsers it becomes impossible to scroll. If a synchronous call takes too much time, the browser may suggest to close the “hanging” webpage.
Many advanced capabilities of XMLHttpRequest , like requesting from another domain or specifying a timeout, are unavailable for synchronous requests. Also, as you can see, no progress indication.
Because of all that, synchronous requests are used very sparingly, almost never. We won’t talk about them any more.
XMLHttpRequest allows both to send custom headers and read headers from the response.
There are 3 methods for HTTP-headers:
Sets the request header with the given name and value .
Several headers are managed exclusively by the browser, e.g. Referer and Host . The full list is in the specification.
XMLHttpRequest is not allowed to change them, for the sake of user safety and correctness of the request.
Another peculiarity of XMLHttpRequest is that one can’t undo setRequestHeader .
Once the header is set, it’s set. Additional calls add information to the header, don’t overwrite it.
Gets the response header with the given name (except Set-Cookie and Set-Cookie2 ).
Returns all response headers, except Set-Cookie and Set-Cookie2 .
Headers are returned as a single line, e.g.:
The line break between headers is always «rn» (doesn’t depend on OS), so we can easily split it into individual headers. The separator between the name and the value is always a colon followed by a space «: » . That’s fixed in the specification.
So, if we want to get an object with name/value pairs, we need to throw in a bit JS.
Like this (assuming that if two headers have the same name, then the latter one overwrites the former one):
POST, FormData
To make a POST request, we can use the built-in FormData object.
The form is sent with multipart/form-data encoding.
Or, if we like JSON more, then JSON.stringify and send as a string.
Just don’t forget to set the header Content-Type: application/json , many server-side frameworks automatically decode JSON with it:
The .send(body) method is pretty omnivore. It can send almost any body , including Blob and BufferSource objects.
Upload progress
The progress event triggers only on the downloading stage.
That is: if we POST something, XMLHttpRequest first uploads our data (the request body), then downloads the response.
If we’re uploading something big, then we’re surely more interested in tracking the upload progress. But xhr.onprogress doesn’t help here.
There’s another object, without methods, exclusively to track upload events: xhr.upload .
It generates events, similar to xhr , but xhr.upload triggers them solely on uploading:
- loadstart – upload started.
- progress – triggers periodically during the upload.
- abort – upload aborted.
- error – non-HTTP error.
- load – upload finished successfully.
- timeout – upload timed out (if timeout property is set).
- loadend – upload finished with either success or error.
Example of handlers:
Here’s a real-life example: file upload with progress indication:
Cross-origin requests
XMLHttpRequest can make cross-origin requests, using the same CORS policy as fetch.
Just like fetch , it doesn’t send cookies and HTTP-authorization to another origin by default. To enable them, set xhr.withCredentials to true :
See the chapter Fetch: Cross-Origin Requests for details about cross-origin headers.
Summary
Typical code of the GET-request with XMLHttpRequest :
There are actually more events, the modern specification lists them (in the lifecycle order):
- loadstart – the request has started.
- progress – a data packet of the response has arrived, the whole response body at the moment is in response .
- abort – the request was canceled by the call xhr.abort() .
- error – connection error has occurred, e.g. wrong domain name. Doesn’t happen for HTTP-errors like 404.
- load – the request has finished successfully.
- timeout – the request was canceled due to timeout (only happens if it was set).
- loadend – triggers after load , error , timeout or abort .
The error , abort , timeout , and load events are mutually exclusive. Only one of them may happen.
The most used events are load completion ( load ), load failure ( error ), or we can use a single loadend handler and check the properties of the request object xhr to see what happened.
We’ve already seen another event: readystatechange . Historically, it appeared long ago, before the specification settled. Nowadays, there’s no need to use it, we can replace it with newer events, but it can often be found in older scripts.
Источник
Archived Forums #
>
.NET Framework Networking and Communication
-
Question
-
0
Sign in to vote
am having an application where its full dependent on wcf services , so…in one of my pages I am trying to bring a huge data from the wcf service , its arround 13000 characters of html . but the problem is that I am getting an error because of the
size of the data , I am having error code 504 of the jxr ( xmlhttprequest object in jquery ) ….can somoene tell me what to do what that ? is it like there is some limit on wcf response ?anyway this is exactly my case ,
http://professionalaspnet.com/archive/2010/09/01/ReadResponse_28002900_-failed_3A00_-The-server-did-not-return-a-response-for-this-request_2E00_.aspx but i dont want to cut the response…anyone can help me with that?Saturday, July 2, 2011 5:36 AM
Answers
-
0
Sign in to vote
Okay , the answer to this was that I am using StatusDescription to pass my wcf result , and httpstatusdescription have a limit of 512 characters so I was exceeding that limit.
-
Marked as answer by
Mazenx
Tuesday, July 12, 2011 11:25 AM
Saturday, July 2, 2011 10:23 PM
-
Marked as answer by
