gpt4 book ai didi

PHP:通过 jQuery ajax 帮助检索 JSON

转载 作者:行者123 更新时间:2023-12-01 06:06:49 25 4
gpt4 key购买 nike

嘿,我有一个脚本正在创建和回显 Magento 产品的 JSON 编码数组。

我有一个脚本使用 jQuery 的 ajax 函数调用此脚本,但我没有得到正确的响应。当执行 GET 请求时,firebug 显示

GET http://localhost.com/magento/modules/products/get.php 200 OK then a **red cross** then 361ms 

这是创建数组的脚本:

 // Load product collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');

$products = array();

foreach ($collection as $product){
$products[] = array("price" => $product->getPrice(),
"name" => $product->getName() );
}

header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($products));

这是我的 jQuery:

<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://localhost.com/magento/modules/products/get.php",
success: function(products)
{
$.each(products,function()
{
var opt = $('<option />');
opt.val(this.name);
opt.text(this.price);
$('#products').append(opt);
});
}
});
})
</script>

我收到了回复,但没有看到任何 JSON。我正在使用 Firebug 。我可以看到有一个 JSON 编码的响应,但响应选项卡是空类型,并且我的选择框没有选项。

任何人都可以看到我的代码有问题吗?

这是我应该得到的响应(当我通过浏览器手动运行脚本时确实得到):

[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"},{"price":"76.0208","name":"Dummy 3"},{"price":"470.6054","name":"Dummy 4"},{"price":"357.0083","name":"Dummy Product 5"}]

谢谢

比利

最佳答案

使用 cache: false 作为 AJAX 参数之一...

我知道当我在 AJAX 中使用 JSON 时,我必须这样做:

                    success: function(data) {
$(".custName, .projectDesc").empty();
for(var x in data) {
$(".custName").append(data[x].message1);
$(".projectDesc").append(data[x].message2);
}

我不确定这是否对您有帮助:)

关于PHP:通过 jQuery ajax 帮助检索 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4993312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com