【问题标题】:Sending values between AJAX and PHP在 AJAX 和 PHP 之间发送值
【发布时间】:2017-01-25 12:26:53
【问题描述】:
    <?php //Site root variable; ?>
<?php require_once("../includes/site_init.php"); ?>

<!DOCTYPE HTML>

<html lang = "en">
    <head>
    <meta charset = "UTF-8">
    <meta name = "viewport" content = "width = device-width, initial-scale = 1">
    <title>Creativity Optimized.</title>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"   integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s="   crossorigin="anonymous"></script>
    <script src="https://npmcdn.com/imagesloaded@4.1/imagesloaded.pkgd.min.js"></script>
    <script src = "_scripts/main.js"></script>
    <!-- <script src = "_scripts/custom.js"></script> -->
    <script src="https://unpkg.com/masonry-layout@4.1/dist/masonry.pkgd.min.js"></script>
    <link rel="stylesheet" href="_css/custom.css">
    <link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,400i,600,700&subset=latin-ext" rel="stylesheet">
    <link rel='shortcut icon' href='_images/favicon.png'>
    </head>

    <body>



        <?php //Header include; ?>
        <?php require("../includes/header_include.php"); ?>


        <section class = "hero">

            <div class = "heroOverlay"></div>

            <ul class = "heroText">

            </ul>

            <ul class = "heroNav">

            </ul>

        </section>



        <section class="welcome-text-container">
            <h1>Welcome to MP</h1>
            <p class="welcome-text">
                MP Creations® is a unique advertising agency and visual design studio.
                We create visual content for almost any medium to tell compelling stories for our clients.
                Our methods rely on creative and strategic thinking. We do it with passion, love and care. See you soon.
            </p>
        </section>

        <div class="content-heading-container">

            <h1 class="content-heading">why us?</h1>

        </div>

        <section id = "mainContent">
                <a href="work.php" title="Forward thinking" class="item-buttons">
                    <img src="_assets/mp_forward_thinking.png" alt="forward thinking" />
                </a>
                <a href="work.php" title="Lets work together" class="item-buttons">
                    <img src="_assets/mp_work_together.png" alt="working together" />
                </a>
                <a href="work.php" title="Projects to play" class="item-buttons">
                    <img src="_assets/mp_play_projects.png" alt="play projects" />
                </a>
                <a href="work.php" title="Nesletter" class="item-buttons">
                    <img src="_assets/mp_newsletter.png" alt="working together" />
                </a>

        </section>


        <section id = "workPreview">
            <div class = "sectionGrids">
                <h2><span>Recent Developments</span></h2>
                <div class = "grid" >

                    <?php $all_portfolio_items = PortfolioItem::find_all();
                        foreach ($all_portfolio_items as $item) { ;?>
                            <div class="grid-item">
                                <a href=work.php data-jobID = '<?php echo $item->id; ?>'>
                                    <img class="grid-img-hover" src='<?php echo '_portfolio-items'.DS.$item->filename; ?>'/>
                                    <div class="title-wrap-hidden"><p class="job-name-hidden"><span><?php echo $item->job_id; ?></span></p></div>
                                    <div class="title-wrap"><p class="job-name"></p></div>
                                </a>
                            </div>
                        <?php ; } ?>

                </div>

                <p><a href="work.php">See More Creations</a></p>
            </div>
        </section>

        <?php //Footer include; ?>
        <?php require("../includes/footer_include.php"); ?>

        <?php
            // chdir("_images");
            // $file = "somefile.txt";
            // $handle = fopen("$file","wt");
            // fwrite($handle,"peaches and cream");
            // fclose($handle);
        ?>


        <script>
        $(document).ready(function(){
            $(document).on('mouseenter', '.grid-item', function(){

                var container = $(this);
                var jobId = container.children().find('.title-wrap-hidden').text();

                // AJAX request
                $.ajax({
                    url: 'db_lookup.php',
                    type: 'POST',
                    data: {jobId: jobId},
                    success: function(data) {
                        // success
                        container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
                                        console.log(data);
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                        // error
                        alert(errorThrown);
                    }
                });
            });


                $(document).on('mouseleave', '.grid-item', function(){

              var container = $(this);
              container.find('.title-wrap').html('<p class="job-name"></p>');

        });
        });
        </script>

</body>

</html>

我有这个 php,可以将一些图像从数据库加载到前端。我现在要做的是,当我将鼠标悬停在(鼠标悬停)图像上时,我想使用 AJAX 将 $item->job_id 传递给另一个 php 脚本,以便我可以使用该 job_id 从另一个图像中查找该图像的名称数据库中的表。

其他 php 脚本可能看起来像这样

    <?php require_once("../includes/site_init.php");
require_once("../includes/site_init.php");

if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
  $job_id = $_POST['jobId'];

  $portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
  echo $portfolio_item_name[0]->name;
}else {
  echo 'result failed';
}
?>

所以 job_id 将来自调用此 php 文件的 AJAX 请求,而 AJAX 本身将从上面的前一个 php 获取 job_id。对于这样的事情,AJAX 会是什么样子? php 脚本需要进行哪些更改?

【问题讨论】:

    标签: javascript php mysql ajax html


    【解决方案1】:

    您可以使用jQueryAJAX$item-&gt;job_id 异步发送到PHP 页面。解决方案是,

    • 将下面的 jQuery 代码放在结束 &lt;/body&gt; 标记的上方,如下所示:

      <!--YOUR CODE-->                
      
      <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
      <script>
          $(document).ready(function(){
              $(document).on('mouseover', '.grid-img-hover', function(){
                  // job id
                  var jobId = $(this).parent().find('.title-wrap').text();
      
                  // AJAX request
                  $.ajax({
                      url: 'yourpage.php',
                      type: 'POST',
                      data: {jobId: jobId},
                      success: function(data) {
                          // success
                          alert(data);
                      },
                      error: function(jqXHR, textStatus, errorThrown){
                          // error
                          alert(errorThrown);
                      }
                  });
              });
          });
      </script>
      </body>
      </html>
      

      注意:不要忘记在AJAX请求的url设置中更改yourpage.php

    • yourpage.php页面上,按以下方式处理你的AJAX请求,

      require_once("../includes/site_init.php");
      
      if(isset($_POST['jobId'])){
          $job_id = $_POST['jobId'];
      
          $portfolio_item_name = Job::find_by_sql('SELECT name FROM '.static::$table_name." WHERE id = '" . $job_id . "' LIMIT 1");
          echo $portfolio_item_name->name;
      }
      

    【讨论】:

    • 我不断得到一个空数组作为查询结果,比如“ var jobId = $(this).parent().find('.title-wrap').text();”没有保存值,我尝试使用 job_id 的原始数字并且它有效。有什么想法吗?
    • @PatrickTraile 这可能是因为您的实际代码块可能与您在问题中给出的代码块不同。根据给定的代码 sn-p,它对我来说工作正常。
    • @PatrickTraile 如果您在.grid-item 上绑定鼠标悬停事件,则使用它来获取jobId,var jobId = $(this).children().find('.title-wrap').text();。但是,由于您将其绑定在 &lt;div&gt; 容器上,而不是图像上,因此它会给您带来不寻常的结果。此外,我用我的代码 sn-ps 测试了你的代码,它工作正常。
    • @PatrickTraile hmm,在这种情况下你需要稍微改变你的 jQuery,http://pastebin.com/N8gu4dcT
    • @PatrickTraile 这是一个逻辑错误。查看您的mouseleave 事件,您正在做.html('&lt;p class="job-name"&gt;&lt;/p&gt;');。所以,当你第一次用鼠标进入 div 元素时,它会在那里显示你的data,但是当你的鼠标离开 div 区域的那一刻,一个事件将被触发并且空白的&lt;p class="job-name"&gt;&lt;/p&gt; 将被放入其中没有文本在 title-wrap div 中。所以下次它不会工作,因为现在没有jobId
    【解决方案2】:

    我会将 jobid 直接写入图像:

    <img src="img.jpg" jobid="test">
    
    
    <script href="jquery.min.js"></script>
    <script>
    window.onload=function(){
    imgs=document.getElementsByTagName("img");
     imgs.forEach(function(let img){
        img.onmouseover=function(){
        jobid=img.jobid;
        $.ajax({
           url:"yourtitle.php",
           method:"GET",
           data:{a:jobid},
           }).done(function(data){
           alert(data);
        });
        });
        };
        });
       };
       </script>
    

    你必须在 jquery.com 上下载 jquery

    还有你的 php

    <?php
    $jobid=$_GET["a"];
    //do whatever
    echo $status;
    ?>
    

    【讨论】:

    • 什么是img.href?也不熟悉“让”我会查一下,我会把那个 onclick 改成 onmouseover 对吗?但是看到 img 标签没有 href 属性是从哪里来的?
    • 另外,传递给 AJAX 的 job_id 在哪里?我是 AJAX 新手,所以我可能会问一些愚蠢的问题。
    【解决方案3】:
    function createRequest() {
        try {
            request = new XMLHttpRequest();
        } catch (tryMS) {
            try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (otherMS) {
                try {
                    request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                    request = null;
                }
            }
        } 
        return request;
    }
    
    window.onload =initpage;
    
    function initpage(){
        $(".job-name").mouseover= fooFunction;
    }
    
    function fooFunction(){
        request=createRequest();
        if(request ==null){
            alert("Error");
        }else{
            var jobID=$(this).text() ;
            var jobId= escape(jobID);
            var url = "yourPhpScript.php?n="+jobId;
            request.onreadystatechange =  function_you_want_to_run_on_success;
            request.open("GET",url,true);
            request.send("null");
        }
    }
    

    你可以使用这个 PHP 脚本

    $b=$_GET['n'];
    
    $query="SELECT * FROM fooTable WHERE colum_name='$a'";
    $result=mysqli_query($d_connection_objject,$query);
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      相关资源
      最近更新 更多