php - php foreach 循环中的 Ajax 调用

标签 php jquery ajax wordpress

我是 ajax 新手,我正在尝试在我的 wordpress 项目中实现它。

ajax 调用工作正常,但问题是 ajax 结果仅显示 foreach 循环中的第一项。我想我在 jQuery 函数中缺少迭代或 $.each 循环?

我不知道...

这是我到目前为止得到的:

我的 WordPress 循环:

{foreach $posts as $item}
{first}<ul class="items">{/first}
<li class="item">
    [....]
        <div class="price__tag">
            <input type="hidden" id="price" value="FRA8" />
            <div id="test-div"></div>
        </div>
    [....]
</li>
{last}</ul>{/last}
{/foreach}

我的 jQuery ajax 函数:

jQuery(document).ready(function() {
var price= jQuery("#price").val();

    jQuery.ajax({
        type: 'POST',
        url: 'http://DOMAIN.COM/wp-admin/admin-ajax.php',
        data: {
            action: 'myAjax',
            greeting: price,
        },
        success: function(data, textStatus, XMLHttpRequest){
            jQuery("#test-div").html('');
            jQuery("#test-div").append(data);
        },
        error: function(MLHttpRequest, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
});

一些背景信息 - 结果来自 SOAP API 请求,并发布在 wordpress 循环中显示的特定产品的价格。

我希望您确实理解我的问题。

非常感谢对此的任何帮助!

编辑 为了完整起见,我还添加了 wordpress 函数:

function add_myscript(){
    wp_enqueue_script( 'myajax.js', get_bloginfo('template_directory') . "/Templates/content/myajax.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myscript' );
function myAjax(){

[…SOAP CLIENT…]

        $result = $soapClient->CarParkAvailRate($parameters);
        $error = $result->Warnings->Code;
        if ($error == '100'){
            $results = "not avail!";
        }
        else {
            $results = $result->CarParks->CarParkRS->PriceCarPark->TotalPrice;
        }
    // Return String
    die($results);
}
catch(SoapFault $fault){
$fault->getMessage();
}
}

// create custom Ajax call for WordPress
add_action( 'wp_ajax_nopriv_myAjax', 'myAjax' );
add_action( 'wp_ajax_myAjax', 'myAjax' );

最佳答案

元素的“id”值必须是唯一的。列表中的每一项都有 <div> “id”为“test-div”的元素。

循环的每次迭代都会重复这两个元素:

<input type="hidden" id="price" value="FRA8" />
<div id="test-div"></div>

您需要它们为每次迭代提供唯一的 id 值。

关于php - php foreach 循环中的 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20669809/

相关文章:

javascript - 自动将动态添加的对象属性(函数)包装在包装函数中

javascript - 了解 jQuery 在内部是如何工作的

javascript - HTML 表格过滤器

php - 显示具有多对多关系的字段 laravel 5.4

php - 安装 Predis 错误 : Download of "nrk/Predis" succeeded, 但它不是有效的包存档

php - 使用 PHP,如何确定使用的是哪个 CMS 或框架?

javascript - 如何验证在框周围移动的可拖动文本?

javascript - 为什么 jqGrid 拒绝使用 OnSelectRow 事件多次调用它的 Ajax 调用

php - 如何调试Ajax响应中的500错误

php - Symfony生产模式错误报告和P​​OST值