0

我有一个向 php 脚本发出 ajax 请求的脚本

    // ajax request for Weather       
    $.ajax({
          type: "POST",
          url: "Json/weatherAPI.php" ,
          data: { 
          postcode: postcode,
          display:'fadeout' ,
          color:'blue' ,
          timed_display:'20'},
          dataType: 'json',   
          success:JsonDataReturned ,

    });

这会调用我的 PHP 脚本,然后查询天气 API 并将 Json 数据返回到我上面的脚本,这一切都很好(下)

         $postcode = $_POST['postcode'];
         $url = "http://www.myweather2.com/developer/forecast.ashx?uac=" . $api . "&output=json&query=" . $postcode ; 
         $response = fopen($url, "r");
         $response = fgets($response, 4096);
         echo $response ;

之后,在同一个 PHP 脚本中,我想用“发布”数据更新我的 SQL 数据库,见下文(数据库已连接)

      $query = 'UPDATE data_weather_control SET ';
      $values = array();

      foreach ( $_POST as $key => $value ) {

                  $query .= ' '.$key.' = :'.$key.',';   // the :$name part is the placeholder, e.g. :zip
                  $values[':'.$key] = $value;           // save the placeholder

      };

      $query = substr($query, 0, -1) ; // remove last , 
      $query .= " WHERE id='dataman' " ;

      $qry = $pdo->prepare($query);
      $qry->execute($values);            // bind placeholder array to the query and execute everything

我相信一切看起来都不错,我知道我有“发布”数据,但它不会更新我的数据库,但是如果我单独运行 php 脚本(没有 ajax 调用)它会更新。我的问题:我的 PDO 语句是否正确,或者 PHP 脚本在作为 ajax 请求调用时不能正常执行?

有什么帮助吗??,

4

1 回答 1

0

PHP doesn't know whether the request is AJAX unless you set a variable and check it yourself, so the request should work. I suspect that PHP is looking for 'POST' variables but your ajax may be sending a JSON string that will have to be decoded. Do a print_r($_POST) and see the difference between running it "alone" or from your ajax call. You might need to parse incoming JSON (in the body of the request). Whatever it is, that print_r will help you see the problem.

于 2013-04-15T19:30:21.290 回答