首页 > 解决方案 > 从浏览器中的对象获取数据

问题描述

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

  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 浏览器中获取数据,该浏览器设法获得响应代码响应。

第 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);
    });
}

第 2 部分:控制台响应:

400 (Bad Request)

第 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"}}

标签: javascriptjquery

解决方案


对 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>


推荐阅读