【问题标题】:Pass Json array into different html divs将 Json 数组传递到不同的 html div
【发布时间】:2019-08-14 12:33:22
【问题描述】:

我想在 3 个不同的 div 中使用我的 Json 数组的前 3 个结果。

ajax.php 返回的数组如下所示:

'{"res":["106"],"base":["190220"]}'

所以我想要 div id:Response1 中的第一个值 "res":["106"] 和 div id:Response2 中的 "base":["190220"]。 我对这方面的了解只有 1%,所以我需要你们的帮助:)

html 和 ajax:

<!DOCTYPE html>
<html>

<form id="resource">
    <input type="number" id="base" name="base" placeholder="Base ID" value="170143" />
    <input type="number" id="lot" name="lot" placeholder="Lot ID" value="110"/>
</form>

<div id="response1"></div>

<div id="response2"></div>

<div id="response3"></div>

<script src="../vendor/jquery/jquery.min.js"></script>
<script>
    (function($){
        function processForm( e ){
            $.ajax({
                url: 'ajax.php',
                dataType: 'html',
                type: 'post',
                data: $(this).serialize(),
                success: function( data ){
                    $('#response1').html( data );
                    console.log( data );
                }
            });
            e.preventDefault();
        }
        $('#resource').change( processForm );
    })(jQuery);
</script>
</body>
</html>

这里是我的 ajax.php 文件:

<?php
require_once('background.php');

if(isset($_POST['base']) and isset($_POST['lot'])){  
    $base = $_POST['base'];    
    $lot = $_POST['lot']; 

    $baseSql = "SELECT * FROM QBS_ABL_VMSCHRP1_SIM where WORKORDER_BASE_ID = '".$base."' AND WORKORDER_LOT_ID = '".$lot."'";
    $baseSTH = $pdo->prepare($baseSql);
    $baseSTH->execute();

    while($row = $baseSTH->fetch(PDO::FETCH_ASSOC)){
        $resArray['res'][] = $row['RESOURCE_ID'];
        $resArray['base'][] = $row['WORKORDER_BASE_ID'];
    }

    if(isset($resArray)){
        json_encode($resArray);
    }  
}

?>

【问题讨论】:

  • 尝试将“dataType: 'html'”改为“dataType: 'json'”
  • @JulyanoFelipe 已经做到了。
  • “等等”在您上次编辑后变得不清楚,"res" 中只有一个值。为了帮助我们了解您的问题,您目前在 div 中获得了什么?
  • 你应该在你的ajax.php中返回/回显一些东西
  • @Kaddath 对不起。编辑帖子以使其清楚。当我使用json_encode($resArray); var_dump(json_encode($resArray)) 结果:'{"res":["106"],"base":["190220"]}'

标签: php html json ajax


【解决方案1】:

通过改变这个来解决它:

(function($){
    function processForm( e ){
        $.ajax({
            url: 'ajax.php',
            dataType: 'json',
            type: 'post',
            data: $(this).serialize(),
            success: function( data, textStatus ){
                res = (data['res']);
                base = (data['base']);
                $('#response1').html( res );
                $('#response2').html( base );
                //console.log( data );
            }
        });
        e.preventDefault();
    }
    $('#resource').change( processForm );
})(jQuery);

【讨论】:

  • 你不需要在data['res']data['base']上使用JSON.stringify,它们已经是字符串了。
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
  • 2018-04-09
  • 2014-07-02
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多