AJAX 发送和接收不同的数据类型


AJAX sending and receiving different data type

我做了一个基本的AJAX函数来调用一个php文件。响应是要插入到我主页的"内容框"中的 HTML

function LoadAjax_alert_display_one(){
    id_alert = <?php echo $id_alerte; ?>;
    $('.preloader').show();
    $.ajax({
        mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
        url: 'ajax/alert_display_one.php',
        data: "id_alerte="+id_alert,
        type: 'GET',
        success: function(data) {
            $('#ajax-content').html(data);
            $('.preloader').hide();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        dataType: "html",
        async: false
    });
}

这工作正常。被调用的文件 'alerts_create.php' 也是 runinng 一个 php 来从数据库中获取数据并使用 while 循环显示它

while ($stmt->fetch()) {
    echo "<tr>";
        echo "<td><a href='#' onclick='LoadAjax_alert_display_one();'>" . $nom_alerte . "</a></td>";
        echo "<td>" . $country . "</td>";
    echo "</tr>";  }

我的问题是我无法正确传递我在 while 循环中创建的链接。$nom_alerte 始终采用循环最后一次迭代的值。所以我的 AJAX 将此作为链接值;任何想法我该怎么做?

为了澄清我的标题:我的问题是将 php 变量发送到被调用的文件('alerts_create.php')并检索 HTML 结果。

解决方案:只需要将 php 变量作为 AJAX 函数参数传递:

function LoadAjax_alert_display_one(id_alerte){
        $('.preloader').show();
    $.ajax({
        mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
        url: 'ajax/alert_display_one.php',
        data: "id_alerte="+id_alerte,
        type: 'GET',
        success: function(data) {
            $('#ajax-content').html(data);
            $('.preloader').hide();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        dataType: "html",
        async: false
    });
}

使用类似这样的东西

<script type="text/javascript">
var data = 'abc=0';
$.post(
  'yoururl.php',
  data
).success(function(resp){
   var json = $.parseJSON(resp);
   console.log(json);
});

在PHP文件中像这样使用

while( $stmt->fetch() ) {
   $data[] = array(
     'link' => 'your link'
   );
}
echo json_encode($data);