jquery .post()return array
質問
悪いタイトルで申し訳ありませんが、これに名前を付ける方法がわかりません。私の問題は、選択ボックスから値を渡すたびに、チェックボックスをチェックするためにこのjQueryイベントをトリガーすることです。基本的にi echo $ res []; Selecctedgr.phpで。 JSONを使用する必要がありますか?どうすればこれを行うことができますか?
メインページ:
$("#group_name").change(function(){
var groupname = $("#group_name").val();
var selectedGroup = 'gr_name='+ groupname;
$.post("selectedgr.php", {data: selectedGroup}, function(data){
$.each(data, function(){
$("#" + this).attr("checked","checked");
});
},"json");
});
php(selectedgr.php):
<?php
include_once '../include/lib.php';
$gr_name=mysql_real_escape_string($_POST['gr_name']);
$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo $res[];
?>
解決
PHPサンプルの最後の行を変更します(echo $res[];
) に:
echo json_encode($res);
json_encode()
マニュアルページはあなたにもっと教えてくれます。
また、@unicronによると、SQLステートメントに渡す前に$ gr_name変数を検証する必要があります。
使用できます:
if(isset($_POST['gr_name'])) {
$gr_name = mysql_real_escape_string($_POST['gr_name']);
}
見る: http://php.net/manual/en/function.mysql-real-escape-string.php PHPマニュアルの詳細については。
他のヒント
使用できます json_encode 任意のデータをJSONに変換する機能。文字列の配列を返したいと仮定すると、json_encodeを使用する方法を次に示します。
<?php
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
クライアント側では、使用できます jquery.postメソッド, 、 このような:
<script type="text/javascript">
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i < data.length; i++) {
$("#" + data[i]).attr("checked", "checked");
}
}, "json");
});
</script>
JSONを使用する場合は、使用してください echo json_encode($res);
しかし、結果を処理するためにJavaScriptで何らかの処理を行う必要があるため、コードが現在機能している場合、あなたが何を得るかは本当に理解していません。
以下のように私の大きな問題を見つけました
の代わりに(前):
$.post("selectedgr.php", {data: selectedGroup}, function(data){
これを行う(後):
$.post("selectedgr.php", selectedGroup, function(data){
私の悪いことを許してください。ああ、yaみんな、実際にmysqlで逃げることについて #group_name
入力フィールドではなく、選択ボックスです。すべてのコメント、提案、ガイドに感謝します。
エリック。