简体   繁体   English

如何直接从json响应ajax请求获取数据

[英]How to get data directly from json response ajax request

My app has a form populated via binding or the methods form.getForm().loadRecord (). 我的应用程序具有通过绑定或方法form.getForm()。loadRecord()填充的表单。

To this form are dynamically added two fields that I want to populate directly from the response of an Ext.Ajax.request. 在此表单中动态添加了两个我想直接从Ext.Ajax.request的响应中填充的字段。

What is the best way to get the data directly from json response ajax request? 直接从json响应ajax请求获取数据的最佳方法是什么?

Ext.Ajax.request({
  url: 'php/read',
  method: 'POST',
  params: {
    'myId': myId,
  },
  success: function (conn, response, options, eOpts) {

      var one = //get directly from request response (json) //????

  },
  failure: function (conn, response, options, eOpts) {
  }
 });

var one = //get directly from request response (json) //???
var two = ...

Ext.ComponentQuery.query('#fieldOne')[0].setValue(one);
Ext.ComponentQuery.query('#fieldTwo')[0].setValue(two);

.

//json 
 data:{
   one: "A",
   two: "B"
 }

EDITED 已编辑

To get response data: 获取响应数据:

 success: function (response, options) {
     var resp = Ext.decode(response.responseText);
     //or
     var resp2 = response.responseText;
 }

With resp I get: 通过resp我得到:

 Object
   success: Object
   data: Array[1]

With resp2 I get: 随着resp2我得到:

   {"success":{"success":true},"data":[{"one":"A","two":"B"}]}

It was supposed to access the data as follows: 应该按如下方式访问数据:

resp.one
//or
resp2.one
//or
resp.data.one

However, it returns 'undefined'. 但是,它返回“未定义”。

What's missing to get 'one' value? 获得“一个”价值的缺失是什么?

You'll need to call a function once your success callback return some data. 成功回调返回一些数据后,您将需要调用一个函数。 This is purely example and may not work exactly as you need, but it'll show you what I mean: 这纯粹是示例,可能无法完全按照您的需要工作,但是它将向您展示我的意思:

Ext.Ajax.request({
    url: 'php/read',
    method: 'POST',
    params: {
        'myId': myId,
    },
    success: function(conn, response, options, eOpts) {
        setFields(response);
    },
    failure: function(conn, response, options, eOpts) {}
});

function setFields(response) {
    Ext.ComponentQuery.query('#fieldOne')[0].setValue(response.one);
    Ext.ComponentQuery.query('#fieldTwo')[0].setValue(response.two);
}

Because you're waiting for your callback function to return, you won't be able to set your variables. 因为您正在等待回调函数返回,所以您将无法设置变量。 So that's why the above needs to happen. 这就是为什么需要进行上述操作的原因。 You could also do it within the callback, but the function is cleaner. 您也可以在回调中执行此操作,但是该函数更加简洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM