使用Ajax进行400次错误请求

时间:2017-11-21 13:12:22

标签: javascript php jquery ajax http-status-code-400

您好我已经尝试了所有可能的内容并阅读了数百个搜索结果,

当我将代码上传到服务器时出现400错误,xampp上的本地代码正常。

我的目标是只使用ajax运行php文件我不需要发布数据但是使用post是我设法让它运行的唯一方法savetodb.php这是我的代码:具体看成功回调对于ajax

<html>
<head>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script
        src="https://code.jquery.com/jquery-3.2.1.js"
        integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>


    <link rel="stylesheet" type="text/css" href="style.css">
    <script>

        $( document ).ready(function() {
           var high = document.getElementById('high');
           var low = document.getElementById('low');
           var closing = document.getElementById('closing');
           var difference = document.getElementById('difference');
            getData();
        });
        function getData() {

            $.ajax({
                type: 'GET',
                url: 'https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles?count=100',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer token goes here'
                },
                success: function(data){
                    $.ajax({
                        type: 'POST',
                        data: data.candles[0],
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        headers: {'Content-Type': 'application/json'},
                        url: 'savetodb.php',
                        success: function(){
                            console.log(data);
                        }
                    })
                }

            }).done(function(data) {
                var highNew = data.candles[0]['mid']['h'];
                var lowNew = data.candles[0]['mid']['l'];
                var closeNew = data.candles[0]['mid']['c'];
                var myArray = data.candles;

                var total = 0;
                var difftotal = 0;
                var diff = 0;
                for (var i = 0, l = data.candles.length; i < l; i++) {
                    total  += parseFloat(data.candles[i]['mid']['c']);
                    diff = data.candles[i]['mid']['h'] - data.candles[i]['mid']['l'];
                    difftotal += parseFloat(diff);
                }
                var diffAvg = difftotal / data.candles.length;
                var avg = total / data.candles.length;
                var dec = avg.toFixed(5)
                var dif = diffAvg.toFixed(10)


                high.innerHTML = highNew;
                low.innerHTML = lowNew;
                closing.innerHTML = dec;
                difference.innerHTML= dif;
            });
        }
        setInterval(getData,5000);

    </script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12"><h1 class="title">EUR/USD</h1></div>

        <div  class="high alert alert-success col-lg-6">
        <span>HIGH</span>
            <span id="high">0.00000</span>
        </div>
        <div class="low alert alert-danger col-lg-6">
            <span>LOW</span>
            <span id="low">0.00000</span>
        </div>
        <div  class="average alert alert-info col-lg-12">
            <span>AVERAGE</span>
            <span id="closing">0.00000</span>
        </div>
        <div  class="average alert alert-info col-lg-12">
            <span>AVERAGE DIFFERENCE</span>
            <span id="difference">0.00000</span>
        </div>
    </div>
</div>
</body>
</html>

And savetodb.php is:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$ch = curl_init();
//
curl_setopt($ch, CURLOPT_URL,"https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles?count=100");
curl_setopt($ch, CURLOPT_HTTPGET , 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'Content-Type: application/json;charset=utf-8',
    'Authorization: Bearer token-cdf86287f59f25f0abf14e215a5b3cb1',
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);
$array = json_decode($server_output,true);
curl_close ($ch);

//print_r($array);
$h = array();
$l = array();
$avg = array();


$con=mysqli_connect("etc","etc","pass","db");

mysqli_query($con,'TRUNCATE TABLE prices');
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


foreach($array['candles'] as $item){
    mysqli_query($con,"INSERT INTO prices (low,high,close) VALUES ('".$item['mid']['l']."','".$item['mid']['h']."','".$item['mid']['c']."')");
}

mysqli_close($con);


?>

1 个答案:

答案 0 :(得分:0)

我通过重构我的第二个ajax调用修复了400错误,将此添加为我对第一个ajax请求的成功调用:

&#13;
&#13;
success: function(data){
                    console.log('ajax success call begins');
                    $.ajax({ url: 'savetodb.php',
                        data: {action: 'test'},
                        type: 'post',
                        success: function(output) {

                        }
                    })
                }
&#13;
&#13;
&#13;

重构PHP页面上的内容以查找POST变量&#34; action&#34;像这样

&#13;
&#13;
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
    }
}

function test(){
 // stuff to do here
}
&#13;
&#13;
&#13;