2015-09-06 184 views
0

我想發送一個php數組到ajax,但它不起作用。說實話,我不知道我做錯了什麼。json_encode返回空php數組

我正在使用json_encode(),它返回null。

我的PHP代碼:

$info = array(); 
$info['NEW YORK CITY'] = array(
'Name' => 'New York City' 
); 

$city = $_POST['city']; 

if (strtoupper($city) === 'NEW YORK CITY') { 

echo "Name: " . json_encode($info['NEW YORK CITY']['Name']) . ".<br>"; 
} else { 
echo "error."; 
} 

我的Ajax代碼:

$('form.ajax').on('submit', function() { 
var that = $(this), 
    url = that.attr('action'), 
    type = that.attr('method'), 
    data = {}; 

    that.find('[name]').each(function(index, value) { 
     var that = $(this), 
      name = that.attr('name'), 
      value = that.val(); 

      data[name] = value; 

    }); 

    //console.log(data); 

    $.ajax({ 
     url: url, 
     type: type, 
     data: data, 
     success: function(response) { 
      //console.log(response); 

      $('form.ajax').html(response); 
     } 
    }).fail(function(jqXHR) { 
     alert(jqXHR.statusText); 
    }); 

return false; 
}); 

定了!我有數組之前的json_encode。它現在起作用,我把數組放在最上面。

+0

我可以看到'print_r($ info);'? – aldrin27

+0

$ info = array(); $ info ['紐約市'] = array('Name'=>'紐約市','Rank'=>'1st,US','Population'=>'8,991,079'); –

回答

0

json_encode接受一個數組作爲參數

,使得其將採取以下

array('key' => 'value') 

這將被髮送作爲適當格式化JSON鍵:值。但是單個值無法正確處理,可能會導致不需要的結果。

+2

json_encode的第一個參數不限於數組。字符串或數字是完全可以接受的輸入。 – curtis1000

+0

雖然是正確的,但要跟上實踐要更直截了當,並且通常是建議的。雖然我的錯誤。 給提問用戶或任何其他觀衆。這裏是json_encode() 的文檔鏈接http://php.net/manual/en/function.json-encode.php –

0

具有以下

$city = $_POST['city']; 
if (strtoupper($city) === 'NEW YORK CITY') { 
    echo json_encode($info['NEW YORK CITY']); 
} else { 
    echo json_encode(array("error.")); 
} 
+0

我得到一個內部服務器錯誤。 –

0

取代你的PHP代碼試試這個,如果這個工程:

$city = $_POST['city']; 

    if (strtoupper($city) === 'NEW YORK CITY') { 
    echo json_encode(['Name' => $info['NEW YORK CITY']['Name'] ]); 
    } else { 
    echo json_encode(['error']); 
    } 

阿賈克斯:

$('form.ajax').on('submit', function() { 
    var that = $(this), 
    url = that.attr('action'), 
    type = that.attr('method'), 
    data = {}; 

    that.find('[name]').each(function(index, value) { 
    var that = $(this), 
     name = that.attr('name'), 
     value = that.val(); 

     data[name] = value; 

    $.ajax({ 
    url: url, 
    type: type, 
    data: data, 
    success: function(response) { 
     //console.log(response); 

     $('form.ajax').html(response); 
    } 
    }).fail(function(jqXHR) { 
    alert(jqXHR.statusText); 
    }); 

    return false; 

    }); 

}); 

你阿賈克斯後應在上然後提交將觸發AJAX功能。