2016-05-21 39 views
0

我的脚本是:没有获得ajax值到一个PHP变量?

<script> 
$(document).ready(function(){ 

    $(".states").on('click','option',function(){ 

     var selValue = $("select[id='stateId'] option:selected").val(); 

      $.post('<?php echo get_template_directory_uri(); ?>/ajax.php', 'val=' + selValue, function (response) { 

       $variable = response; 
       //alert("Variable value is: "+$variable); 

      }); 

    }); 

}); 

选择活动地点 选择国家 选择国家 选择城市
<div class="col-sm-9"> 


     <?php 
     $a2 = $variable; 
     print_r($a); die; 
     $args = array(
      'meta_key' => 'state', 
      'meta_value' => $a2, 
      'post_type' => 'event', 
      'posts_per_page' => -1 
     ); 
     $the_query = new WP_Query($args); 

     // The Loop 
     if ($the_query->have_posts()) { 
      echo '<ul>'; 
      while ($the_query->have_posts()) { 
       $the_query->the_post(); 
       echo '<li><h2>' . get_the_title() . '</h2></li><br>'; 
      } 
      echo '</ul>'; 
     } else { 
      echo 'no posts found'; 
     } 
     /* Restore original Post Data */ 
     wp_reset_postdata(); 

     //echo do_shortcode('[qem]'); ?>   

    </div> 
</div> 
+0

更改''val ='+ selValue'为{val:selValue} –

+0

实际上我想根据状态过滤帖子。并通过ajax post()获取状态值。我需要把它变成一个php变量。或者将这个值传递给数组值''meta_value'=> $ a2“。 – Saral

+0

首先你需要改变我的建议,并且比它自己填充的变量要多。但如果它是一个PHP变量,你不能。 –

回答

0

做这样的事情:

你需要像{ val : selValue }送价值,并在ajax.php你必须存储的值$_POST当你经过它IKE $.post,绝返回响应。

返回响应后,它被设置为H1标签文本。

阿贾克斯:

$.post('<?php echo get_template_directory_uri(); ?>/ajax.php', { val : selValue }, function (response) { 
    variable = response; 
}); 

PHP

$variable = "<script>document.write(variable);</script>"; 

你可以试试这个,让我知道发生什么事。

+0

是的,先生在h1中获得选定的值。但如何可以将它传递到的$ args =阵列( \t \t \t \t 'meta_key'=> '状态', \t \t \t \t 'meta_value'=> $ A2, \t \t \t \t 'post_type'=>'事件”, \t \t \t \t 'posts_per_page'=> -1 \t \t \t);在“$ a2”的地方 – Saral

+0

** _你无法按照你想的方式完成这项工作。_ ** –

+0

但您可以使用表单值来提交,以便您可以在该数组中获取它。 –