简体   繁体   English

jQuery AJAX JSON请求中未捕获的类型错误

[英]Uncaught type error in jQuery AJAX JSON request

My WordPress AJAX process is completing successfully, but the returned JSON object is displaying the following error in Chrome Devtools: Uncaught TypeError: Cannot read property 'vehicle' of undefined. 我的WordPress AJAX进程成功完成,但是返回的JSON对象在Chrome Devtools中显示以下错误:Uncaught TypeError:无法读取未定义的属性“ vehicle”。 I am not sure why this is happening. 我不确定为什么会这样。 The parsed JSON data is being outputted as an object, which should be correct. 解析的JSON数据将作为对象输出,这应该是正确的。 All of the JavaScript and PHP code is detailed below. 下面详细介绍了所有JavaScript和PHP代码。 The sample valid JSON object can be viewed here: https://jsfiddle.net/roaq9ew1/ . 可以在此处查看示例有效的JSON对象: https : //jsfiddle.net/roaq9ew1/

/**
 * Create 'Get Registration' button and append to vehicle-registration list item
 */
var getRegoButton = document.createElement('button');
getRegoButton.setAttribute('id', 'get-rego');
getRegoButton.setAttribute('class', 'get-rego');
getRegoButton.innerHTML = 'Get Registration';

var vehicleRegistrationWrapper = document.getElementById('field_2_6');
vehicleRegistrationWrapper.appendChild(getRegoButton);

/**
 * Function to retrieve Carjam API data via AJAX
 */ 
jQuery(document).ready( function($){
  $(".vehicle-details").hide();

  $("#get-rego").click(function(e){
    e.preventDefault();

    $(".vehicle-details").show();

    plate = $("#input_2_6").val();

    $.post(
      "/wp-admin/admin-ajax.php", 
      {
        "action": "get_vehicle",
        "plate": plate,
      }, 

      function(response) {
        obj = JSON.parse(response);
        console.log(typeof obj);
        console.log(obj.idh.vehicle);
      }
    );
  });

  function populateVehicleDetails(vehicleDetail, apiData) {
     var carData = ".vehicle-details span id="+vehicleDetail+"";
     $(carData).val(apiData);
  }
});

/**
 * Function to handle API call to Carjam for vehicle registration data
 */
add_action( 'wp_ajax_get_vehicle', 'prefix_ajax_get_vehicle' );
add_action('wp_ajax_nopriv_get_vehicle', 'prefix_ajax_get_vehicle');
function prefix_ajax_get_vehicle() {
  $plate = $_POST["input_2_6"];
  $testApikey = "C9DBAF2CD487DE38EC1AE78C09329E6711BF644C";
  $testApiUrl = "http://test.carjam.co.nz/api/car/?plate=";

  $url  = $testApiUrl.$plate."&key=".$testApiKey;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $data = curl_exec($ch);
  curl_close($ch);
  $oXML = new SimpleXMLElement($data);

  echo json_encode($oXML);

  wp_die();
}

In your ajax call you have set your post field as plate, but you arent referencing that in your php. 在您的ajax调用中,您已将您的post字段设置为plate,但您没有在php中引用它。

Change this: 更改此:

$plate = $_POST["input_2_6"];

to this: 对此:

$plate = $_POST["plate"];

You also have errors in your ajax success function: 您的ajax成功函数中也有错误:

  function(response) {
    obj = JSON.parse(response);
    console.log(typeof obj);
    console.log(obj.idh.vehicle);
  }

Declaring the variable obj this was gives it a global scope and is not good practice. 声明变量obj这将使其具有全局作用域,这不是一个好习惯。 It generates a strict JavaScript warning. 它会生成严格的JavaScript警告。 You shouldn't use this variant, you should declare it var obj . 您不应使用此变体,而应将其声明为var obj

Having said that in this case that whole line is unneccessary. 话虽如此,在这种情况下,整个生产线都是不必要的。 You don't need to JSON.parse the response, you simply add json as the datatype of yur ajax post and jQuery will do the rest. 您不需要JSON.parse响应,只需将json添加为yur ajax post的数据类型,其余的将由jQuery完成。 You can access the returned data in response.vehicle etc. 您可以在response.vehicle等中访问返回的数据。

If you paste your response JSON in to JSON parser you'll get a better idea of the structure and you will see that response.vehicle is actually an object, so depending on what bits of data you want to extract it might be easier to assign that to another variable. 如果将响应JSON粘贴到JSON解析器中,您将对结构有更好的了解,并且您会看到response.vehicle实际上是一个对象,因此取决于要提取的数据位,可能更容易分配到另一个变量。 Here's an example using a slight reworking of your code: 这是一个稍微修改代码的示例:

$.post( "/wp-admin/admin-ajax.php", { "action": "get_vehicle", "plate": plate }, function( data ) {
    var vehicle = data.idh.vehicle;
    console.log( vehicle.make ); // HOLDEN
    console.log( vehicle.model );  // VECTRA
}, "json"); // Specifying "json" here tells your ajax call what type of data to expect back from the server

As your javascript knowledge improves you may want to revisit this and improve your response handling by adding some methods to the your object to make it easier to perform set actions with the returned data, but that's a lesson for a little further down the line. 随着您的javascript知识的提高,您可能希望通过在对象中添加一些方法来简化此操作并通过对对象添加一些方法来改善响应处理,从而更轻松地对返回的数据执行设置操作,但这是一个更深入的学习。

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

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