开发者

one JSON call returned with many?

开发者 https://www.devze.com 2023-01-29 05:20 出处:网络
My question is... How to make json have 1 call back with several objects. I will use this example of 3 values to be returned... Here is the calclickM.php file, but I can not understand why it is not

My question is... How to make json have 1 call back with several objects.

I will use this example of 3 values to be returned... Here is the calclickM.php file, but I can not understand why it is not woking...

    <?php  
$choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d"); 
$con = mysql_connect("localhost","root","xxxxxx");  
if (!$con)  {  die('Could not connect: ' . mysql_error());  }  
mysql_select_db("inverters", $con);  

$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); 
$row = mysql_fetch_assoc($res); 
$dayPowerP = array ('dayPowerP');
?>

<?php 
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx");  
if (!$con)  {  die('Could not connect: ' . mysql_error());  }  
mysql_select_db("inverters", $con);  
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); 
$row = mysql_fetch_assoc($res); 
$monthPowerP = array ('monthPowerP');
?>

<?php 
$choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx");  
if (!$con)  {  die('Could not connect: ' . mysql_error());  }  
mysql_select_db("inverters", $con);  

$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error()); 
$row = mysql_fetch_assoc($res); 
$yearPowerP = array ('yearPowerP');
?>
<?php
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
?>

Here is the Jquery I am using to post and the json

    <script type="text/javascript">
$(document).ready(function () {   
$('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) {
            var myDate = $(this).datepicker('getDate');
            $('#apDiv1').html($.datepicker.formatDate('DD, d', myDate));
            $('#apDiv5').html($.datepicker.formatDate('MM', myDate));
            $('#apDiv7').html($.datepicker.formatDate('yy', myDate));           
            $.ajax({  
            type: "POST",   
            url: "calclickM.php",                  
            data: {choice: dateText}, 
            data开发者_JAVA百科Type: "json",  
            success: function(json_data) {  
            $('#apDiv2').html(json_data['dayPowerP']);  
            $('#apDiv6').html(json_data['monthPowerP']);  
            $('#apDiv8').html(json_data['yearPowerP']);  
           } 
        })           
    }});
}); 

Thanks,

Alan


At first the load method you are calling is making an AJAX GET request to your server. You probably support both POST and GET requests in your PHP script.

Secondly you have some errors in the your $.ajax calls. There are some unterminated strings, the data variable you are using as ('#apDiv9').html(data) isn't defined and if it was, it will be probably contain JSON data that you can't directly put in an HTML element.

Last, but not least, the second attempt won't make your code faster. A browser can only support a limited number of parallel ajax requests (1-2). You are still making the same number of requests and some of them need to wait for the others to complete. Re-design your code so that you return everything in a single call.


Not a solution to your immediate problem, but your code needs some serious refactoring. The level of repetition here hurts my eyes. The second code block, the one with the ajax-calls, could be changed to something like this:

var pages = [
  { url: "dayPower.php",   div: "#apDiv4"  },
  { url: "dayGraph",       div: "#apDiv2"  },
  { url: "monthPower.php", div: "#apDiv6"  },
  { url: "monthGraph",     div: "#apDiv9"  },
  { url: "yearPower.php",  div: "#apDiv8"  },
  { url: "yearPower",      div: "#apDiv10" }
};

for ( var i=0; i<pages.length; i++ ) {
  $.ajax({ 
    type: "POST",  
    url: pages[i].url,                 
    data: { choice: dateText}, 
    dataType: "json", 
    success: function(json_data ) 
      (pages[i].div).html(data).show(); // Did you mean json_data here?
    }
  });
}

The case is similar with the first piece of code in your question.

Once again, I know it won't solve the actual problem, but it will make it easier to implement the solution when you (or someone else) finds it.

EDIT

On second thought, I can see at least one strange thing: in the success-function you call the parameter json_data, but you access a variable that you've called data. Did you intend to name them the same thing?


There is a way to do what you are asking, but you will need to handle the results yourself. Essentially all your Ajax calls have the same parameters, but different resultsets. So first, the client side code that does the magic:

$.post('datePacked.php', {choice: dateText}, function(data) {
    $('#apDiv2').html(data['dayPower']);
    $('#apDiv4').html(data['dayGraph']);
    $('#apDiv6').html(data['monthPower']);
    $('#apDiv9').html(data['monthGraph']);
    $('#apDiv8').html(data['yearPower']);
    $('#apDiv10').html(data['yearGraph']);
});

If you refactored your HTML so taht you actually match the div Ids with the result of your JSon response, you can simplify the call even further:

$.post('datePacked.php', {choice: dateText}, function(data) {
    $.each(data, function(id, value) {
        $('#'+id).html(value);
    });
});

On the server side your new datePacked.php needs to return a JSON result that provides a hash of names to content. Essentially it will look something like this:

{ "dayPower" : "<p>My Content</p>", "dayGraph" : "<p>Day graph</p>", ... }

The ellipsis is there for you to fill in the remainder of the content. Choosing meaningful id names for your HTML elements is not only good practice, it can save you a lot of repitition if you take advantage of it. An example of that would be the second form of the client example. This is a case where the content has to be JSON for it to work--unless you want to split up a DOM returned by the server.


I’m not exactly sure what you’re asking, but here’s a couple of points:

  1. $('#apDiv2').load('dayPower.php', {choice: dateText} does the same thing as $.ajax({type: "POST", url: "dayPower.php", data: { choice: dateText}. Both $.ajax and $.load make HTTP requests via JavaScript, which is what “AJAX” means.

  2. Your second block of example code has some basic syntax errors. Here’s the first $.ajax call corrected:

    $.ajax({ 
        type: "POST",  
        url: "dayPower.php",                 
        data: { choice: dateText}, 
        dataType: "json", 
        success: function(json_data ) { // “{” added to start the function block
            ('#apDiv2').html(data).show(); 
        }
    }) // “})” added to end the object literal and function call
    


if you never need call any of this separately, why not just make one ajax call to a php file, package all your data into a multidimensional array, convert to json, and send back to the client.

Once you have this json, you can then break it up with js and figure out what goes where on your front end.

Depending on how much data you're getting it may take a while. If it's a huge query, then breaking it up into several little calls be actually be better. Its asynchronous so at least parts of your page will be loading. while other parts are gathering data.

0

精彩评论

暂无评论...
验证码 换一张
取 消