jQuery変数をfunction.phpに送信して、いくつかのphp関数で使用することは可能ですか? AJAXまたはおそらく経由。
テーマ関連で、プラグインを使用していません。
例えば。クリック時にjQueryを介して「クライアント側」に追加されたポストCSSクラスがいくつかあります。
このクラスを「サーバー側」で使用して、テーマの任意のページに渡すことができますか?
ワードプレス環境
まず、このタスクを達成するために、要求をサーバーにプッシュする jQuery スクリプトを登録してキューに入れることをお勧めします。これらの操作は、wp_enqueue_scripts
アクション フックにフックされます。同じフックwp_localize_script
に、任意の Javascript を含めるために使用されていることを示す必要があります。このようにして、フロント エンドで使用可能な JS オブジェクトが存在します。このオブジェクトは、jQuery ハンドルによって使用される正しい URL を保持します。
以下をご覧ください。
ファイル: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so18550905_enqueue_scripts' );
function so18550905_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR SCRIPT FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}
ファイル: jquery.ajax.js
このファイルは ajax 呼び出しを行います。
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
ファイル: functions.php 2/2
最後に、functions.php ファイルに、ajax 呼び出しによってトリガーされる関数があるはずです。接尾辞を覚えておいてください:
これらのサフィックスとアクションがアクションの名前を構成します。
wp_ajax_myaction
またwp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so18550905_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so18550905_wp_ajax_function' );
function so18550905_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
それが役に立てば幸い!
不明な点があればお知らせください。
はい、AJAX を使用して jQuery 変数を送信できます。(または任意の Javascript 変数)
JSON.stringify(any-Variable-Here) を実行するだけで、対応する文字列を取得できます。
次のような任意の php ファイルに AJAX 経由で値を送信します。
var toBeSent = JSON.stringify($($('#selector')[0]).attr('class'));
$.ajax({
type: "POST",
url: 'function.php',
data: toBeSent,
success: function(data){ // any action to be performed after function.php returns a value.
},
dataType: 'text'
});
注: ここでは項目を文字列化して、単純な分割を行うことでサーバー側の変数にアクセスできるようにしました。
できますよ
$('element').click(function(e){
e.preventDefault();
var el = $(this);
//do stuff on click
//send this elements class to the server
$.ajax({
url: "some.php",
data: {
class: el.attr('class')
},
success: function(r){
alert("class name sent successfully to some.php");
}
});
});
別のオプションは$.post()です
$(document).ready( function() {
$('#myDiv').click(function(){
var myClass = $(this).attr('class');
var url = 'page.php';
$.post(url, { class: myClass })
.done( function() {
alert('class sent to ' + url);
});
});
});