dongtong0796 2016-02-05 13:57
浏览 24
已采纳

使用ajax和php显示文本

I'm just trying to do a simple thing in ajax but it does not work. I just want to display a text when i click on the input button

ajax.js

jQuery(document).ready(function($) {
$('#insertForm').change(function(){
//on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
var req=$('#insertForm').val();
//requête ajax, appel du fichier function.php
$.ajax({
  type: "POST",
  url: "lib/function.php",
  data: "insertForm="+req,
  dataType : "html",
  //affichage de l'erreur en cas de problème
  error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
      },
      //function s'il n'y a pas de probleme
  success:function(data){
    $('.coucou').empty();
    $('.coucou').prepend(data.coucou)
  }
});
});
}); 

html.php

<div class="coucou"></div>
<button type="button" class="btn btn-success btn-xs" name="insertForm" id="insertForm" style="margin-top: 5px;;">
    <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
</button>

function.php

if(isset($_POST['insertForm'])){
    echo "coucou";
}
  • 写回答

2条回答 默认 最新

  • douqi3064 2016-02-05 14:14
    关注
    jQuery(document).ready(function($) {
        $('#insertForm').click(function(){
        //on recupere la valeur de l'attribut value pour afficher tel ou tel resultat
            var req=$('#insertForm').val();
            //requête ajax, appel du fichier function.php
            $.ajax({
              type: "POST",
              url: "lib/function.php",
              data: "insertForm="+req,
              dataType : "html",
              //affichage de l'erreur en cas de problème
              error: function(XMLHttpRequest, textStatus, errorThrown) {
                      alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
                  },
                  //function s'il n'y a pas de probleme
              success:function(data){
                $('.coucou').empty();
                $('.coucou').text(data);
              }
            });
        });
    }); 
    

    You need to use .click() and not .change() and also, in the success, you receive only a string not an object so you just need to write data directly (with .text())

    Copy my code because i have also add ; that you had forgotten. (It's work, I tested)

    Another point you use .val() on #insertForm but there is no value attribute in your html. So var req is an empty string

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容