通过Ajax调用带参数的PHP函数表单URL

时间:2014-05-20 15:42:01

标签: javascript php jquery ajax cakephp

请查看以下代码

.... ctp文件中的Javascript代码......

<script type="text/javascript">
$(document).ready(function(){


   $( ".btn-danger" ).click(function(){
        console.log("Red Button");
        var toclose = $(this).parent().parent();
        $.ajax({
          url: "../img/media.jpg",
        }).done(function() {
            console.log( "The act has been done");
            toclose.toggle();
          });
   }); 


   $( ".btn-success" ).click(function(){
      console.log("Red Button");
      idOfButton = $(this).attr('id');
      var toclose = $(this).parent().parent();
      $.ajax({
        url: "../img/media.jpg",
      }).done(function() {
          increment(idOfButton);
            alert(idOfButton);
      console.log( "The act has been done");
          toclose.toggle();
      });
 }); 

  $( ".xy" ).click(function(){

    $(this).find("#enside1").toggle();
    $(this).find("#ptside1").toggle();
    console.log(this);
  });

      function xxx(id)
  {
      alert(id);
  }

  function increment(uniqueWord)
  {
      $.ajax({
          url: "http://localhost/cake2/flip2/correct",
                  data: {word: uniqueWord}

        }).done(function() {
            console.log( "The act has been done");
            toclose.toggle();
          });

    }

});


</script>

请考虑此功能

function increment(uniqueWord)
  {
      $.ajax({
          url: "http://localhost/cake2/flip2/correct",
                  data: {word: uniqueWord}

        }).done(function() {
            console.log( "The act has been done");
            toclose.toggle();
          });

    }

这里我试图在PHP文件中调用一个方法。该方法包含一个参数。

public function correct($word)
        {
            $this->Flip2->correctAnswer(89,$word);

        }

但是将参数值传递给PHP方法存在问题。它根本不起作用。如果我从“所有”的地方删除参数,只需调用url: "http://localhost/cake2/flip2/correct",这可以正常工作。通过Ajax调用将值传递给PHP方法时我做错了什么?

2 个答案:

答案 0 :(得分:1)

您可以在网址中传递该字词:

function increment(uniqueWord)
  {
  $.ajax({
      url: "http://localhost/cake2/flip2/correct/" + uniqueWord,
      //...

答案 1 :(得分:0)

作为另一种解决方案,您可以将ajax调用更改为发布请求,并从$ this-&gt; request-&gt; data

获取控制器中的数据
 $.ajax({
      url: "http://localhost/cake2/flip2/correct",
      data: {word: uniqueWord},
      type: 'post'
    }).done(function() {
        console.log( "The act has been done");
        toclose.toggle();
      });

控制器将

public function correct()
    {
        $this->Flip2->correctAnswer(89,$this->request->data['word']);

    }