有人可以告诉我为什么这个请求不会执行成功代码吗?
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
console.log(JSON.stringify({markets: post_data}));
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(){
console.log("IT WORKED");
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 10000);
});
当我检查console.log(JSON.stringify({markets: post_data}));
的输出时,会在google chrome中获得此结果:
{“markets”:[{“market_number”:1,“name”:“GBPUSD”},{“market_number”:2,“name”:“EURUSD”}}}
但我永远不会将“IT WORKED”打印到控制台上,这意味着它永远无法正常工作。
进一步检查我在我的php中发了一个if语句,检查是否发布了任何内容
if(!empty($_POST))
echo "POSTED!!!!!";
else
echo "NOT POSTED";
但我总是在屏幕上打印“Not POSTED”。
任何想法?
感谢您的帮助。
答案 0 :(得分:3)
使用此代码:
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
console.log(JSON.stringify({markets: post_data}));
$.ajax({
url: 'signals.php/',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(){
console.log("IT WORKED");
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 10000);
});
答案 1 :(得分:1)
您可以轻松地在POST
请求中传递ajax
数据而不JSON.stringify
。
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = '&market_number1=1&name1='+$(".trade_window .market_name_1").text().trim()+'&market_number2=2&name2='+$(".trade_window .market_name_2").text().trim();
$.ajax({
url: 'signals.php',
type: 'POST',
data: post_data,
dataType: "json",
success: function(){
console.log("IT WORKED");
}
});
}, 2000);
});
答案 2 :(得分:1)
如果你想使用json.stringyfy并在php端读取数据..这是正确的方法
数据:{json:JSON.stringify({markets:post_data})}
$(document).ready(function(){
var post_data = [];
//$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()},];
console.log(JSON.stringify({markets: post_data}));
$.ajax({
url: 'signals.php',
type: 'POST',
data: {json: JSON.stringify({markets: post_data})},
dataType: "json",
done: function($msg){
console.log("IT WORKED");
}
});
}, 2000);
});
现在在PHP中你可以做任何事情
$json = json_decode($_POST["json"]);
print_r($json);
或
if(isset($_POST["json"])){
$json = json_decode($_POST["json"]);
if(!empty($json))
echo "POSTED!!!!!";
else
echo "NOT POSTED";
}
DINS