0

以前に質問を投稿しましたが、コードが間違っていたため、機能しませんでした。タイトルが示すように、DB からいくつかのデータを取得し、それを div にエコーします。クリックすると、このデータを取得してjavascriptファイルに渡し、変数を設定し、これらの変数をphpファイルに送信してDBに挿入します。ページが更新されないように、これをすべて実行したいと思います。ここに私のdivがあります:

echo "<div><a href='javascript:void(0);' onClick='wish(".$title.", ".$link."); 
return false;'>Add to Wish List</a></div>";

タイトルとリンクは、データベースから取得したデータです。JS スクリプト:

$(function() {
function wish(title, link){
var title = //how to set this to the title passed??
    var link = //how to set this to the link passed??
}
$.ajax({
  type: "POST",
  url: "wish_list.php",
  data: title and link //what's the correct syntax to pass these two vars???
  success: function(){
    alert("Item added to your wish list");
}
});
});

PHPのwish_list.phpファイルでは、次を使用します。

if (isset($_POST['title']) && isset($_POST['link'])){
   echo"<script>
     alert("variables passed");
   </script>";
}

それで、私はどれくらい離れていますか?私は何が欠けていますか、それともすべて間違っていますか?

4

2 に答える 2

0

すでに jquery を使用しているので、最初に html をクリーンアップします。

echo "<div><a class=\"wishable\" href=\"#\" data-wishlist-title=\"$title\" data-wishlist-link=\"$link\">Add to Wish List</a></div>"

html からすべての js を削除しました。jQuery を使用している場合、機能を html にインライン化する本当の理由はありません。jQuery.attr必要なデータにアクセスするために、またはでアクセスできるデータ属性でエンコードしましたjQuery.data。のクラスも追加して、wishableすべてのリンクにクリック ハンドラーをアタッチできるようにしました。

だから、あなたが持っていた古いインライン関数を接続することはできません:

$(function() {
    $(document).on('click.wishable', 'a.wishable', function (e) {
         var $this = $(this), // the <a />
             title = $this.data('whishlistTitle'), // pull the title from the data attr
             link = $this.data('wishlistLink');  // pull the link from the data attribute

         e.preventDefault(); // prevent default link handling

         $.ajax({
           type: "POST",
           url: "wish_list.php",
           data: {"title": title, "link": link },
           success: function(){
             alert("Item added to your wish list");
           }
         });         
    });
});

リンクとタイトルを取得する方法は次のとおりです。

title = $this.data('whishlistTitle')
link = $this.data('wishlistLink')

データ属性で使用jQuery.dataする場合、属性名の変換があります。プレフィックスが削除されdata-、残りがハイフン付きからキャメルケースに変換されます。さらに、値はネイティブの JavaScript タイプに変換されます。これは、実際には数値ではない数値文字列 (たとえば、0 のパディングされた製品 SKU など) では非常に重要ですが、あなたの例では問題になりません。ただし、これはdataよりも遅くなりattrます。

jQuery.attr代わりに使用することもできますが、完全な属性名を使用する必要があります。

title = $this.attr('data-whishlist-title')
link = $this.attr('data-wishlist-link')

ここにフィドルがあります:http://jsfiddle.net/hyFXM/1/

テストのために、渡したものをエコーバックして警告することができます。したがって、jQuery.ajax次のようになります。

         $.ajax({
           type: "POST",
           url: "wish_list.php",
           data: {"title": title, "link": link },
           success: function(text){
             alert(text);
           }
         });

そして、あなたのphpは次のようになります:

if (isset($_POST['title']) && isset($_POST['link'])){
   echo 'SUCCESS - $_POST[\'title\'] =' . $_POST['title'] . ' $_POST[\'link\'] = '. $_POST['link'];
} else {
   echo 'FAIL WHALE!!!!!!';
}
于 2013-02-06T22:00:14.643 に答える
0

近いですが、使用するデータ形式を決定する必要があります。JSON を使用する場合は、PHP でjson_encodejson_decodeを使用し、JavaScript でJSON.stringifyjQuery.parseJSONを使用できます。

変数を PHP に渡し、PHP から JSON を取得する

PHP:

$url = json_decode($_POST['url']); // You have a php array of the details now
var_dump($url);

JS:

var url = { 
    title: 'Home Page', 
    link: location.href
};

jQuery.ajax({
    type: 'POST',
    url: "wish_list.php",
    data: JSON.stringify(url),
    dataType: "json",
    success: function(data){ console.log(data); }
});

PHP から JavaScript に変数を渡す

以下は、Drupal のやり方に触発されたものです。jQuery をインクルードした後、他のスクリプトをインクルードする前に、これをインクルードします。

<script>
  var Globals = { 'settings': {}, 'somethingelse': {} };
  jQuery.extend(Globals.settings, {'phpVersion':'<?php print phpversion() ?>', link:'http://www.google.com', title:'Google'});
</script>

次に、JavaScript で設定を読み書きできます。

// Add this device's window width
jQuery.extend(Globals.settings, {'deviceWidth':$(window).width()});

// Now print everything Global.settings has including the variable set by PHP
console.dir(Global.settings);

// Or get a specific variable:
console.log('This server is running PHP ' + Globals.settings.phpVersion);
于 2013-02-06T21:53:03.377 に答える