• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

134
Views
Resultado de la matriz Ajax como opción Seleccionar - indefinido

Soy nuevo en AJAX / JSON, y estoy luchando para analizar una respuesta de matriz AJAX en un menú desplegable <select> .

Mi resultado se ve bien, pero a pesar de que investigué bastantes tutoriales en línea y probé varias formas de devolver el resultado, cada uno de ellos da como resultado que las options del menú desplegable se muestren como undefined .

resultado AJAX

 [{"property_code":"AGGCO","name":"Office Name"}]

Nota: puede haber hasta 100 entradas en la matriz.

jQuery

 $('#unit').on('change', function() { var unitID = $(this).val(); if (unitID) { $.ajax({ type: 'POST', url: '../../controllers/admin_addNewUser_units_offices.php', data: 'action=unit_office_dropdown&unit_id=' + unitID, success: function(response) { console.log(response); var len = response.length; $("#office").empty(); for (var i = 0; i < len; i++) { var code = response[i]['property_code']; var name = response[i]['name']; $("#office").append("<option value='" + code + "'>" + name + "</option>"); } } }); } else { $('#office').html('<option value="">Select Business Unit first</option>'); } });

¿Alguien podría explicar qué estoy haciendo mal, por favor? Gracias

almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Su código parece razonable, suponiendo que analice el JSON

se puede simplificar

NOTA: Si desea "Por favor, seleccione", puede usar .html() que también vaciará la selección. Si no vacía, la próxima vez tendrá las nuevas opciones agregadas a las anteriores.

 const response = `[{ "property_code": "AGGCO", "name": "Office Name"}]`; // for testing const opts = JSON.parse(response); // not needed if you deliver application/json $("#office") .html(new Option("Please select", "")) .append(opts .map(({ property_code, name }) => new Option(name, property_code)))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <select id="office"></select>

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error