发送数据并仅使用ajax加载div

时间:2015-01-11 10:26:18

标签: jquery ajax

如何使用jquery-ajax发送数据后,在当前文件的特定div中加载外部文件的特定div?

例如,如何将#first置于#solution1内,将第二个置于#solution2

HTML:

<div id="button">button</div>
<div id="solution1">solution1</div>
<br><br>
<div id="solution2">solution2</div>

JQUERY / AJAX:

$(function(){
    $("#button").click(function(){
        $.post("proces.php"
        , { id: 299 } 
        ,function (result) {
            $("#solution1").html(result); // this works
            //$("#solution1").html(result .first); // this does not work
            //$("#solution2").html(result .second); 
        }// end function result
        );//end post
    });//end click
})

PROCES:

<?php
include("../../externs/includes/connexio.php");

$id = $_REQUEST['id'];
$result = mysqli_query($con, "SELECT * FROM bookmarks
                              WHERE id = '$id' ");

while ($row = mysqli_fetch_array($result)) {
    $minut = $row["minut"];     
?>

<div class="first"> <?php echo $minut; ?> </div>
<div class="second"> <?php echo $minut . ' something else'; ?> </div>

<?php 
}
?>

2 个答案:

答案 0 :(得分:1)

在php中

include("../../externs/includes/connexio.php");

$id = $_REQUEST['id'];
$result = mysqli_query($con, "SELECT * FROM bookmarks
                              WHERE id = '$id' ");

$first=array();
$second=array();

while ($row = mysqli_fetch_array($result)) {
    $minut = $row["minut"];     
$tmp='<div class="first">'.$minut'.</div>';
$tmp2='<div class="second">'.$minut . ' something else </div>';
array_push($first,$tmp);
array_push($second,$tmp2);

}
echo json_encode(array('first'=>$first,'second'=>$second));

并在html中

$(function(){
    $("#button").click(function(){
        $.post("proces.php"
        , { id: 299 } 
        ,function (result) {
            var res=$.parseJSON(result);
            $("#solution1").html(res.first); 
            $("#solution2").html(res .second); 
        }
        );
    });    })

答案 1 :(得分:0)

你可以试试这个:

$("#solution1").html($(result).find('.first').get(0));
$("#solution2").html($(result).find('.second').get(0));

var str = '<div><span class="one">1</span><span class="two">2</span></div>';

$('button').click(function(){
   $('body').append($(str).find('.one').get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>alert</button>

即使你也可以这样使用.load()

$("#button").click(function(){
    $("#solution1").load("proces.php .first", { id: 299 });
    $("#solution1").load("proces.php .second", { id: 299 });
});