开发者

JSON data output from PHP

开发者 https://www.devze.com 2023-02-28 07:21 出处:网络
I have connected to a mysql database and I am trying to use jquery to populate a drop down menu usi开发者_C百科ng data from the database and JSON.

I have connected to a mysql database and I am trying to use jquery to populate a drop down menu usi开发者_C百科ng data from the database and JSON.

I do not have much experience with JSON, but I have read many articles and searched the web for tutorials.

In my PHP to connect to the database, the last lines format and output the JSON correctly:

$response = $_GET["jsoncallback"] . "(" . json_encode($colors) . ")";

echo $response;

In the javascript, I use:

$.getJSON("db.php?jsoncallback=?", function(data){ //loop that populates the drop down });

I have jquery set up to grab the JSON and populate the drop down, which is also working correctly. However, the JSON data that is created in the PHP is outputted at the top of my generated page.

i.e., ([{"color":"Purple"},{"color":"Red"},{"color":"Blue"},{"color":"Pink"},{"color":"Yello"}])

How do I still access the jsoncallback without outputting the JSON on my page?


It looks like you are using the same file to generate the JSON output aswell and generate your normal pages, which is why the JSON will output at the top of the page.

Try wrapping the JSON output in an if statement that prevents output unless you reqire it, ie when you make an AJAX request, or move the JSON output to another file such as ajax.php that is specifically for handling AJAX requests. Simple example below.

Updates JS, passing over a new actions param.

$.getJSON("ajax.php?jsoncallback=?", { action: 'get_colors' },  function(data){ //loop that populates the drop down })

New PHP file ajax.php

// Include required other php files, etc
switch ($_GET['action']) {

    case 'get_colors':
        $response = $_GET["jsoncallback"] . "(" . json_encode($colors) . ")";
        echo $response;
    break;

 }


Is the following inside a script block? If not, it needs to be.

echo $response;

Like so:

echo "<script>{$response}</script>";
0

精彩评论

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