如何使用ajax从div id中提取数据?

时间:2015-03-28 18:23:20

标签: javascript php jquery html ajax

我正在试图弄清楚如何做到这一点,但我没有线索。 我需要使用ajax从div获取文本,然后使用php通过SMTP发送它,但我相信我只需要知道如何制作ajax部分。

假设我有这个:

<div id="trajeto-texto1">
     <span id="resultado">
         <div class="calculo"><label>Distância: 0.00 Km</label></div>
         <div class="calculo"><label>Duração: 0 min.</label></div>
         <div class="calculo"><label>Custo: R$ 0,00</label></div>
     </span>                    
</div>

我需要解析div id“trajeto-texto”中的每个文本,或者在span id“resultado”中解析。

它就像一个php回声,但是在javascript中。

控制台调试,显然没有与表单相关的内容:

Failed to load resource: the server responded with a status of 404 (Not Found)
main.js:61 Uncaught TypeError: undefined is not a function
main.js:60 You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
33209.html:9 Uncaught ReferenceError: J is not defined
VM7253:10 Uncaught TypeError: Cannot set property 'geometry' of undefined
dados-do-formulario.js:100 Uncaught SyntaxError: Unexpected token :
http://sitesdemo.mghospedagem.com/ivam-entregas/3/images/bg.png Failed to load resource: the server responded with a status of 404 (Not Found)
33209.html:1 Uncaught ReferenceError: J is not defined
33209.html:9 Uncaught ReferenceError: J is not defined
33209.html:3 Uncaught ReferenceError: J is not defined
33209.html:6 Uncaught ReferenceError: J is not defined
http://sitesdemo.mghospedagem.com/ivam-entregas/3/33209/css Failed to load resource: the server responded with a status of 404 (Not Found)

更新

好的,所以我决定尝试一下,但仍然没有成功:

 $(document).ready( function(){ //Quando documento estiver pronto
    $('#btnEnviar').click( function(){ /* Quando clicar em #btn */
        /* Coletando dados */
        var nome  = $('#nome').val(); 
        var email = $('#email').val(); 

var distance = $("#distance").text();
var duration = $("#duration").text();
var costs = $("#costs").text();         


        var msg   = $('#txtDetalhes').val();                                            
        var end1 = $('#1').val(); 
        var end2 = $('#txtEnderecoChegada').val(); 



        if(nome.length <= 3){           
            alert('Informe o seu nome');                        
            return false;           
        }    
        if(email.length <= 3){           
            alert('Informe o seu email');                        
            return false;           
        }  


        if(end1.length <= 3){           
            alert('Informe o endereço de partida');                        
            return false;           
        }                         
        if(end2.length <= 5){           
            alert('Informe o endereço de chegada');                        
            return false;           
        }      
        if(msg.length <= 5){           
            alert('Informe os detalhes');                    
            return false;           
        }                     





        /* construindo url */

/*

var urlData = "&nome=" + nome + "&email=" + email +  "&end2=" + end2 + "&distance=" + distance + "&duration=" + duration + "&costs=" + costs + "&msg=" + msg + "&end1=" + end1;

*/








 // extract all the values

    var data = [];
    $('#resultado span').each(function (index, item) {
        var id = $(item).attr('id');
        data[id] = $(item).text();
    });

    // do we have all the values?
    console.log(data);

    // POST the values to backend.php (adjust the URL).
    $.ajax({
        type: "POST",
        url: "sendmailivam.php",
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
});




var urlData = { 
    "nome": nome,
    "email": email,
    "distance": distance,
    "duration": duration,
    "costs": costs,
   "msg": msg,
    "end1": end1,
    "end2": end2
};


        // Ajax 


        $.ajax({
             type: "POST",
             url: "sendmailivam.php", // endereço do phpmailer
             async: true,
             data: urlData, // informa Url
             success: function(data) { // sucesso 
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { // antes de enviar 
                 $('.loading').fadeIn('fast'); 
             },
             complete: function(){ // completo 
                 $('.loading').fadeOut('fast');
             }
         });




    });    
}); 

再次尝试,我相信我现在不会错过任何一点,我怀疑问题是:数据是空的。看看我是怎么做的:

$(document).ready(function() { //Quando documento estiver pronto
     $('#btnEnviar').click(function() { /* Quando clicar em #btn */
         /* Coletando dados */
         var nome = $('#nome').val();
         var email = $('#email').val();



         /*
                  var distance = $("#distance").text();
                  var duration = $("#duration").text();
                  var costs = $("#costs").text();
                 */


         // extract all the values

         var data = [];
         $('#resultado span').each(function(index, item) {
             var id = $(item).attr('id');
             data[id] = $(item).text();
         });

         // do we have all the values?
         console.log(data);



         var msg = $('#txtDetalhes').val();
         var end1 = $('#1').val();
         var end2 = $('#txtEnderecoChegada').val();



         if (nome.length <= 3) {
             alert('Informe o seu nome');
             return false;
         }
         if (email.length <= 3) {
             alert('Informe o seu email');
             return false;
         }


         if (end1.length <= 3) {
             alert('Informe o endereço de partida');
             return false;
         }
         if (end2.length <= 5) {
             alert('Informe o endereço de chegada');
             return false;
         }
         if (msg.length <= 5) {
             alert('Informe os detalhes');
             return false;
         }

         //Construindo URL
         var urlData = {
             "nome": nome,
             "email": email,
             "data": data,
             "msg": msg,
             "end1": end1,
             "end2": end2
         };


         /*
            var urlData = {
                      "nome": nome,
                      "email": email,
                      "distance": distance,
                      "duration": duration,
                      "costs": costs,
                      "msg": msg,
                      "end1": end1,
                      "end2": end2
                  };

         */



         // Ajax 

         $.ajax({
             type: "POST",
             url: "sendmailivam.php", // endereço do phpmailer
             async: true,
             data: urlData,


             // informa Url
             success: function(data) { // sucesso 
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { // antes de enviar 
                 $('.loading').fadeIn('fast');
             },
             complete: function() { // completo 
                 $('.loading').fadeOut('fast');
             }
         });




         // do we have all the values?
         console.log(data);




     });
 });

5 个答案:

答案 0 :(得分:4)

我会稍微解释你的问题,也许这就是你想要的:

1如何从HTML中提取值?

诀窍是添加一个dom元素,以便更容易选择实际值。

<div id="trajeto-texto1"> 
    <span id="resultado">
        <div class="calculo">Distância: <span id="distance">1.00</span> Km</div>
        <div class="calculo">Duração: <span id="duration">2</span> min.</div>
        <div class="calculo">Custo: R$ <span id="costs">3,00</span> </div>
    </span>    
    <button id="SubmitButton">Send</button>
</div>

这允许选择&#34;值&#34;无后顾之忧(从标签文本中拆分或正则表达值)。

您只需使用$("#distance")通过ID使用jQuery选择dom元素。 要获取您附加的值.text();

var distance = $("#distance").text();
var duration = $("#duration").text();
var costs = $("#costs").text();

或者更好地使用.each()迭代dom元素并构建数据对象,如下所示:

// extract the values
var data = [];
// iterate over dom element inside span (= item)
$('#resultado span').each(function (index, item) {
    // from this item, get the id
    var id = $(item).attr('id');
    // from this item, get the text, which is the value
    data[id] = $(item).text();
});

console.log(data); // browser console = debug display = open it with key F12

控制台输出为:[distance: "1.00", duration: "2", costs: "3,00"]

好的,我们确保data包含我们要发送的值...现在:让我们发送。

2如何将值发送到PHP?

嗯,这取决于。您可以执行POST或GET请求。嗯,让我们去POST:

// your data looks like this, we got this already
var data = [distance: "1.00", duration: "2", costs: "3,00"];

// post data array to your PHP backend
$.post("backend.php",
    data: data,
    function(data,status){
      // do anything with response
});

完整示例:

http://jsfiddle.net/b6w0ckmj/2/

$('#SubmitButton').click(function (evt) {

    // extract all the values

    var data = [];
    $('#resultado span').each(function (index, item) {
        var id = $(item).attr('id');
        data[id] = $(item).text();
    });

    // do we have all the values?
    console.log(data);

    // POST the values to backend.php (adjust the URL).
    $.ajax({
        type: "POST",
        url: "/echo/html/",
        data: data,
        success: function (response) {
            console.log(response);
        }
    });
});

答案 1 :(得分:1)

Jens A. Koch,它没有工作。我正在使用这样的javascript:

var urlData = "&nome=" + nome + "&email=" + email +  "&end2=" + end2 + "&distance=" + distance + "&duration=" + duration + "&costs=" + costs + "&msg=" + msg + "&end1=" + end1;


        /* Ajax */
        $.ajax({
             type: "POST",
             url: "sendmailivam.php", /* endereço do phpmailer */
             async: true,
             data: urlData, /* informa Url */
             success: function(data) { /* sucesso */
                 $('#retornoHTML').html(data);
             },
             beforeSend: function() { /* antes de enviar */
                 $('.loading').fadeIn('fast'); 
             },
             complete: function(){ /* completo */               
                 $('.loading').fadeOut('fast');
             }
         });
    });    
});

答案 2 :(得分:1)

@ user3692451这是您的评论

数据需要成为一个对象:

var urlData = { 
    nome: nome,
    email: email,
    end2: end2,
    distance: distance,
    duration: duration,
    costs: costs,
    msg: msg,
    end1: end1
};

答案 3 :(得分:1)

如果您需要从div中提取所有文本,无论它们如何嵌套,您都可以执行以下操作:

function getTexts(rootNode){
    var stack = Array.prototype.slice.call(rootNode.childNodes,0);
    var texts = [];
    var currentNode;
    while(currentNode = stack.pop()){
        if(currentNode.nodeType === Node.TEXT_NODE && 
           currentNode.textContent.match(/[A-z0-9]/)
          ){
            texts.push(currentNode.textContent);
        }
        if(currentNode.childNodes.length > 0){
            stack.push.apply(stack, 
                Array.prototype.slice.call(currentNode.childNodes,0)
            );
        }
    }
    return texts;
};

Demo on JSFiddle

答案 4 :(得分:1)

解决了它,我不得不将元素放在一个表单中,并在元素后面使用隐藏的输入。所以它是这样的:

    <div id="trajeto-texto1"> 
 <form method="post" action="33209/33209.html">

        <span id="resultado" style="font-weight:bold">


        <div class="calculo">Distância: 1.00 Km</div>
        <div class="calculo">Duração: 2 min.</div>
        <div class="calculo">Custo: R$ 3,00 </div>
    </span>  
   <input id="resultado" type="hidden" name="resultado" />

   </div>

还必须在javascript中进行一些调整,但没有什么与Jens A. Koch的回答完全不同。