2016-07-14 121 views
0

我正在使用jQuery AJAX從PHP返回一個由一些JavaScript,PHP和HTML組成的字符串。jQuery Ajax返回多個數據

我能成功地做到這一點用下面的代碼:

header("Content-Type: text/html"); 
echo $content; 

$.ajax({ 
    type: 'POST', 
    url: url, 
    data: data, 
}).done(function(result) { 

}).fail(function(jqXHR, textStatus, errorThrown) { 
    console.log(jqXHR, textStatus, errorThrown); 
}); 

我現在的問題是,我要沿着這串返回其他一些簡單的值也是如此。

但是,如果我使用json_encode發送這些值的數組,它會打破我的字符串,並不會成功。

我怎樣才能發送一個值作爲字符串(沒有json_encode)和一些其他值json_encode? (所以我不json_encode我的字符串)

EDIT1:

下面是格式問題1:

return 'autoOpenPopup: '.!empty($options["autoOpenPopup"]) ? $this->int_to_bool($options["autoOpenPopup"]) : $this->int_to_bool(false) . PHP_EOL .'; 

2:

return '.!isset($options["popupInit"]) ? 

       $playerId.' = jQuery("#'.$wrapperId.'").hap(settings); 

      ':' 

       if(hasLocalStorage){ 

        if(!localStorage.getItem("hap_popup_fixed")){ 
         '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings); 
        } 
       }else{ 
        '.$playerId.' = jQuery("#'.$wrapperId.'").hap(settings); 
       } 
+0

那麼把你的字符串放入數組然後'json_encode'呢? – Chay22

+0

我試着json_encode只是在我的字符串,它打破。把它放在數組中似乎並沒有改變任何東西:http://pastie.org/10907465 – Toniq

+0

那麼,你應該發佈實際的代碼來找出是什麼讓它破壞。 – Chay22

回答

3

,最好的辦法是json_encode數據並串在一起;

$data = array('some', 'array', 'elements'); 

$string = 'my string'; 

$data2 = array('more', 'data'); 

然後你把所有的人都在一個陣列:

$result = array(); 
$result['data1'] = $data; 
$result['string'] = $string; 
$result['data2'] = $data2; 

最後json_encode數組:

echo json_encode($result); 

然後你讀的結果JS:

$.ajax({ 
    type: 'POST', 
    url: url, 
    data: data, 
}).done(function(result) { 
    var jsonResult = $.parseJSON 
    var data1 = result.data; 
    var data2 = jsonResult.data2; 
    var str = jsonResult.string; 

}).fail(function(jqXHR, textStatus, errorThrown) { 
    console.log(jqXHR, textStatus, errorThrown); 
}); 
+0

我試着json_encode只是在我的字符串,它打破了。 (我猜是因爲它長時間混合使用php,html,javascript) – Toniq

+0

可以和我們分享一下字符串嗎? –

+0

我還將包括根據我的示例讀取數據的代碼 –

0

header('Content-type:application/JSON'); echo json_encode($ data,true);

and in your $ .ajax({... dataType:'json'});