从浏览器中的对象获取数据

时间:2020-01-23 21:18:08

标签: javascript jquery

如何从浏览器获取对象/从浏览器获取存储在对象中的数据?

  1. 用户在填写带有不良信用卡号的表单(我正在测试的情况)后按下提交按钮,这将触发jQuery函数SubmitAPI()(下面的代码)。
  2. Google Chrome控制台显示400 Bad Request错误(因为信用卡号不正确),以及显示包含信用卡数据被拒绝的对象的API响应(以下响应)
  3. 我特别需要抓取"response_type":"D","response_code":"U20","response_desc":"INVALID CREDIT CARD NUMBER",因为我想向用户显示此错误消息。如何在jQuery中做到这一点?
  4. 我已经尝试了好几个小时才能弄清楚这一点。交易成功(信用卡批准)时,我使用response.response.response_type获取响应类型。但是,如果信用卡号错误,此尝试将导致“未定义”。因此,我只想从设法获得响应代码响应的Google Chrome浏览器中获取数据。

PART 1:jQuery代码(直接来自API文档-除非我将信用卡号更改为错误的数字)

  function SubmitAPI() {
    var settings = {
        "url": 
    "https://sandbox.forte.net/api/v3/organizations/org_ID/locations/loc_ID/transactions",
        "method": "POST",
        "headers": {
            "X-Forte-Auth-Organization-Id": "org_ID",
            "Authorization": "ID",
            "Content-Type": "application/json"
        },
        "data": JSON.stringify({ "action": "sale", "authorization_amount": 102.45, "subtotal_amount": 99.95, "billing_address": { "first_name": "Jennifer", "last_name": "McFly" }, "card": { "card_type": "visa", "name_on_card": "Jennifer McFly", "account_number": "41111sdf11111111", "expire_month": "12", "expire_year": "2017", "card_verification_value": "123" } }),
    };

    $.ajax(settings).always(function (response) {
        console.log(response);
    });
}

PART 2:控制台响应:

400 (Bad Request)

PART 3:浏览器中的响应对象:

{"location_id":"loc_241789","action":"sale","authorization_amount":102.45,"entered_by":"59ae172b3bd78bed493ecd5892975764","billing_address":{"first_name":"Jennifer","last_name":"McFly"},"card":{"name_on_card":"Jennifer McFly","last_4_account_number":"1111","masked_account_number":"****1111","expire_month":12,"expire_year":2017,"card_type":"visa"},"response":{"environment":"sandbox","response_type":"D","response_code":"U20","response_desc":"INVALID CREDIT CARD NUMBER"}}

1 个答案:

答案 0 :(得分:3)

使用错误处理程序进行Ajax调用,并能够毫无问题地获得错误消息。

var settings = {
  "url": "https://sandbox.forte.net/api/v3/organizations/org_381529/locations/loc_241789/transactions",
  "method": "POST",
  "headers": {
    "X-Forte-Auth-Organization-Id": "org_381529",
    "Authorization": "Basic NTlhZTE3MmIzYmQ3OGJlZDQ5M2VjZDU4OTI5NzU3NjQ6ZWUwZTZiZDA4ZThlMWNhNWQ3MzUyNGU0ZWU5ZDFjNTg=",
    "Content-Type": "application/json"
  },
  "data": JSON.stringify({
    "action": "sale",
    "authorization_amount": 102.45,
    "subtotal_amount": 99.95,
    "billing_address": {
      "first_name": "Jennifer",
      "last_name": "McFly"
    },
    "card": {
      "card_type": "visa",
      "name_on_card": "Jennifer McFly",
      "account_number": "41111sdf11111111",
      "expire_month": "12",
      "expire_year": "2017",
      "card_verification_value": "123"
    }
  }),
};

$.ajax(settings).error(function(xhr) {
  console.log("Error", xhr.responseJSON.response.response_desc);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>