json数据未显示在jquery中


json data not shown in jquery

Html代码为:

<select  name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<input type="text" name="sale" id="saleprice"  class="form-control" />
<input type="text" name="sale" id="saletax"  class="form-control" />
<input type="text" name="sale" id="avalqty"  class="form-control" />

在我的Js页面上:

function getPrice(val)
{
   $.ajax({
     type: 'post',
     url: 'get_sales_price.php',
     data: {
       get_option:val
     },
     success: function (response) {
        var valuesar = response.split("|");
        $('#saleprice').val(valuesar[0]);
        $('#saletax').val(valuesar[1]);
        $('#avalqty').val(valuesar[2]);
     }
   });
}

这是我的PHP页面数据:

$data = array();    
$values=$variable1['value1'].'|'.$variable2['value2'].'|'.$variable3;
array_push($data, $values);
echo json_encode($data);

#saleprice上的值为:["61.25#avalqty上的值:155"][strong>,而#saletax上的值则为:1。#saletax值正确。。如何获取#saleprice:["61.2561.25#avalqty:155"]155

我认为您可以做的是从服务器返回一个key-value对象,并在成功处理程序中使用它。在您的情况下,您将返回一个具有单个字符串值的数组

$data = array();    
$data['price'] = $variable1['value1'];
$data['tax'] = $variable2['value2'];
$data['qty'] = $variable3;
echo json_encode($data);

然后

function getPrice(val) {
  $.ajax({
    type: 'post',
    url: 'get_sales_price.php',
    data: {
      get_option: val
    },
    dataType: 'json',
    success: function(response) {
        console.log(response)
      $('#saleprice').val(response.price);
      $('#saletax').val(response.tax);
      $('#avalqty').val(response.qty);
    }
  });
}

在成功函数中尝试JSON.parse(响应)。您在数组中发送字符串,因此需要首先对其进行解析,使用数组索引访问该字符串,然后拆分该字符串。否则,您可以直接在php代码中回显字符串,而不是将其推送到数组中,然后使用json_encode。

所以你的php代码应该是

$values=$variable1.'|'.$variable2.'|'.$variable3;
echo $data;

通过这种方式,您将在ajax响应中收到一个字符串,您可以直接拆分该字符串。

更改

var valuesar = response.split("|");

 var valuesar = response[0].split("|");

嘿,您可以按照以下方式使用代码

<?php
$data = array();    
$values='6.15'.'|'.'52.22'.'|'.'55.25';
array_push($data, $values);
$rr=json_encode($data);

$ltrim = ltrim($rr, '["');
$rtrim = rtrim($ltrim, '"]');

// echo $rtrim;

?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {

var response='<?php echo  $rtrim ?>';
console.log(response);
var valuesar  = response.split("|");

$('#saleprice').val(valuesar[0]);
$('#saletax').val(valuesar[1]);
$('#avalqty').val(valuesar[2]);
 console.log(valuesar[0]);
 });
 </script>
 <!DOCTYPE html>
 <html>
 <body>
<form>
<input type="text" name="saleprice" id="saleprice" >
<input type="text" name="saletax" id="saletax" >
<input type="text" name="avalqty" id="avalqty" >
</form> 
</body>
</html>