0

こんにちは私は現在私のphpページ(下記)でjavascriptを実行しています、そしてそれは私が必要とする各データで出てきますこれをmysqlデータベースに接続する方法はありますか?(私はjavascriptを初めて使用します)

<script>
 var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
  var item = allItems[i];
  console.log('Current item: %o', item);

}
</script>

'itemsArrayは保存関数から来ています'

function save(){

var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];

var newItem = {};
var num = document.getElementById("num").value;

newItem[num] = {
    "methv": document.getElementById("methv").value
    ,'q1': document.getElementById("q1").value,
    'q2':document.getElementById("q2").value,
    'q3':document.getElementById("q3").value,
    'q4':document.getElementById("q4").value,
    'comm':document.getElementById("comm").value
};


oldItems.push(newItem);

localStorage.setItem('itemsArray', JSON.stringify(oldItems));


});

ありがとう

PS私はすでにデータベース設定のための接続を持っています

4

1 に答える 1

1

ajax / jsonリクエストを使用してデータをphp関数に投稿し、データベースに関連するすべての作業をphpで実行します。次に、この呼び出されたjs関数でキャッチされる成功または失敗のステータスを返します。その後、javascriptを使用して成功または失敗のメッセージを表示できます。

例:

jQueryライブラリを含める:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

jQueryを使用したajaxリクエストのスクリプト:

    var path = 'http:/your_url/your_php_script_file.php';
    var data = 'json_data=' + JSON.stringify(newItem[num]);
        $.ajax({
            url: path,
            type: "POST",
            data: data,
            cache: false,
            success: function ($returm_msg){
                alert($returm_msg);
            }
        });

データベースに保存/更新するためのPHP:

$receive_value = json_decode($_POST['json_data'], true));

次のような値が得られます

$receive_value['methv'],$receive_value['q1'],....,$receive_value['comm'];

次に、データベースに操作を保存します。

$result = mysql_query("INSERT INTO .....") or die(mysql_error());
if($result){
    return "Success!"; // if not function then simply echo "Success!";
}else{
    return "Failure!"; // if not function then simply echo "Failure!";
}

便利なリンク:

  1. http://www.bennadel.com/resources/presentations/jquery/demo21/index.htm
  2. http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
于 2013-03-15T14:45:18.050 に答える