Iron Ajax - How to access Response from on-response function?

不问归期 提交于 2020-01-02 03:39:27

问题


I have this element:

<template>
...
<iron-ajax 
   id="ajax" 
   url="..." 
   handle-as="json" 
   verbose=true 
   last-response={{ajaxResponse}} 
   loading="{{cargando}}"
   on-response="_handleResponse"> 
</iron-ajax>

<div id="resultado"></div>
</template>

<script>
    Polymer({
        ...

        _handleResponse: function(event){
            console.log("_handleResponse... ");
            // this.$.resultado.innerHTML = event.detail.innerHTML;
        }
    });
</script>

The response I see in Firebug is:

<p>Hello word</p>

I want to access the response in _handleResponse function in order to set it as innerHTML of the resultado div, but nothing works.

I have tried:

  • event.detail.innerHTML
  • event.detail.response
  • event.detail.xhr.response
  • event.detail.xhr.responseText
  • event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)

If I debug and watch e.detail.response value when in on-response function:

In network tab I can see the response (simple 'hello'):


回答1:


The response data is in fact returned in event.detail.response of the <iron-ajax>.response event. Your response field is null because you've misconfigured <iron-ajax>.handleAs. When you set it to json, the Accept-Type header is set to application/json and any response would be parsed with JSON.parse(). If your server ignores Accept-Type and sends whatever it wants, <iron-request> will attempt to parse the response as JSON and fail, causing a null response body per the spec. Note that hello and <p>Hello</p> are not valid JSON strings.

If you want to receive plaintext data, set <iron-ajax>.handleAs to text (the default is json).

Demo of <iron-ajax handle-as="text">

Demo of <iron-ajax handle-as="json">


  • event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)

The question you linked asks about the <iron-ajax>.error event, which has a different event detail than the <iron-ajax>.response event.

When <iron-ajax> receives a server response, it fires the response event with the corresponding <iron-request> as the event detail.

If the request fails for any reason, <iron-ajax> fires the error event with an object (containing the iron-request via the request attribute, and the underlying error via error) as the event detail.



来源:https://stackoverflow.com/questions/40850079/iron-ajax-how-to-access-response-from-on-response-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!