我做了大量的研究,并一直在兜圈子。我创建了一个拍卖应用程序,需要"实时出价"过程:
所以我需要能够执行GET语句来找到当前的最高出价(这将需要一些验证)然后我需要执行一个 POST 语句(再次事先执行验证)
困难:
我找不到定期更新当前出价的解决方案。 即每 3-5 秒检查一次出价是否正确或只是更新它
有很多相互矛盾的信息,作为PHP和Laravel的新手,我真的很卡住。我确实很欣赏其他类似问题的数量,但没有一个充分解释需要什么或进入所需的详细程度。如此之多,以至于我开始认为jQuery/AJAX不是完成此任务的正确操作。
主.js(加载在所有 php 文件的标头中)
var delay = 5000;
var getCurrentHighestBid = function() {
// perform validation here, if necessary
var url = '/items'; // insert your URL here
$.get(url, null, handleGetCurrentHighestBidResponse);
};
var handleGetCurrentHighestBidResponse = function(response) {
// check for nulls in response here, handle exceptions, etc
// then insert your bid data into the DOM, which may look
// something like:
$('.winner').html(response.Html);
setTimeout(getCurrentHighestBid , delay);
};
项目控制器.php(代码片段)
public function show($id)
{
$item = Item::find($id);
//find higest bid fo item_auction id
$winningBid = Item::find($id)->bids()->max('bid_amount');
//var_dump($item);
return View::make('items.show', compact('item', 'winningBid'));
}
show.blade.php (view) (snippet)
<h4 id="winner">{{$winningBid }}</h4>
这是 javascript/jQuery 的理想候选者。
编辑:我已经更新了代码,使其更简单,更健壮。GET函数从响应中调用(延迟),这也处理来自服务器的延迟。
所以基本上:
- 调用服务器
- 等待响应
- 处理响应
- 等待(由延迟时间设置)
- 重复步骤 1
GET可能看起来像这样(需要jQuery):
var delay = 5000;
var getCurrentHighestBid = function() {
// perform validation here, if necessary
var url = ''; // insert your URL here
$.get(url, null, handleGetCurrentHighestBidResponse);
};
var handleGetCurrentHighestBidResponse = function(response) {
// check for nulls in response here, handle exceptions, etc
// then insert your bid data into the DOM, which may look
// something like:
$('.bid-details').html(response.Html);
setTimeout(getCurrentHighestBid, delay);
};