Вопрос

У меня есть скрипт для обновления таблицы баз данных. Мне нужно вернуть массив JSON и обновить несколько таблиц с помощью jQuery.

мой скрипт PHP:

$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);

jQuery Code:

$("button").live("click", function(event){
                    event.preventDefault();
                    $.getJSON("startsearch.php",{ searchId: $(this).val() }, function(data){
                        alert(data[0].status);
                    });

Теперь ... проблема в том, что если я использую $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) Сценарий выполняется, и я получаю хорошее предупреждение со значением неопределенной. Если я добавлю параметр «json», сценарий больше не выполняется. Я попытался использовать Getjson, но опять же, та же проблема.

У кого -нибудь есть идеи? Я отчаянно нуждаюсь ... это беспокоит меня почти неделю, и мне до сих пор не удалось его решить.

Это было полезно?

Решение

В вашем файле PHP обязательно установите правильный тип контента:

header("Content-type: application/json; charset=utf-8");

так что jQuery может правильно eval Ответ в объект JSON.

Другие советы

Вы можете добраться до данных ответа следующим образом:

alert(data.status);
alert(data.results);
alert(data.totalResults);

Пожалуйста, не используйте предупреждение, установите Firebug в свой Firefox или включите консоль JavaScript в Chrome или Safari. После этого вы можете использовать console.log(data);

Я предполагаю, что данные не массивы. Также посмотрите на exmaple exmaple на документах jQuery http://docs.jquery.com/ajax/jquery.getjson

Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.

I always write my AJAX request like this:

$.post(URL,
  { PARAM },
  function(data){
    try {
      var r = JSON.parse(data);
      //this for your code above
      alert (r.status); //should be 'COMPLETED'
    }
    catch (e) {
      //data is not in json format, or there are another exception in try block
      //do something about it
      alert('Exception occured, please check the data!');
    }
});

When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top